What the Pythons docs means by "container" ?

Chris Angelico rosuav at gmail.com
Tue Feb 17 19:49:46 EST 2015


On Wed, Feb 18, 2015 at 11:30 AM, candide <c.candide at laposte.net> wrote:
> Python Language Referenceb (PLR) is expected to give formal and acurate definition, not "descriptive term to talk about things".

In a lot of ways, technically accurate definitions can be useless,
where sloppy but descriptive terms are useful. For instance, we can
distinguish between an integer (doesn't contain things) and a list
(does contain things), and then categorize sets, tuples, and
SimpleNamespace()s with the latter, and exceptions, strings, and
functions with the former. But technically, an exception has a
reference to something else (a traceback), and could thus be said to
contain it, and a function always has a reference to its global
namespace (which itself contains that function), etc, so any specific
and formal definition is likely to be quite useless. Also, a string
can be said to "contain" a whole lot of substrings - "bcd" in "abcde"
is True - even though those substrings don't actually have to exist as
objects, so it's impossible for the string to retain references to
those substrings. Even worse, a string always contains *itself*, which
makes a definition based on the 'in' operator conflict entirely with a
definition based on a real-world analogy involving a box with stuff in
it.

So, what's a container? It's a thing that you put other objects into.
That's all the definition you really need, most of the time. If you
want a better definition, you first need to ask yourself: What aspect
of "containerness" matters here? Why do you need to distinguish
container from non-container? If you want to know whether the 'in'
operator can be used, then ask whether the 'in' operator can be used.
If you want to know whether it's possible for this object to be part
of a reference cycle, ask whether it's possible for this object to be
part of a reference cycle. If you want to know whether this is a
useful way to return multiple results from a function, then ... you
get the idea. They're all very different aspects of containers, and
not all containers have all those aspects. (For instance, a tuple
can't [1] have a reference to itself. You can't get a reference cycle
without having some other type of object, such as a list, involved.)
"Is this a container?" isn't often a useful question to ask.

ChrisA

[1] You can use C code to create a tuple containing itself, but in C,
you're most welcome to shoot yourself in the foot in other ways, too.



More information about the Python-list mailing list