What the Pythons docs means by "container" ?

Cameron Simpson cs at zip.com.au
Tue Feb 17 16:39:54 EST 2015


On 17Feb2015 13:21, candide <c.candide at laposte.net> wrote:
>Official Python documentation very frequently invokes a mysterious *container* data structure. The PLR manual explains :
>--------------------------
>Some objects contain references to other objects; these are called containers.
>--------------------------

And this is the basic thing, as you understand.

>So containers contain : what a great definition!

Shrug. It is a useful descriptive term when you want to talk about things. You 
might keep in mind that a "container"'s _primary_ purpose is usually its 
containing function. So a list. But not so some arbitrary object, even though 
most objects have references to other objects.

[...]
>So I was considering a Python range object NOT being a container: indeed, range(10**6) does NOT store 10**6 integers and range(10**6) has a small memory footprint
[...]
>Then, mining the official docs, I realized that the collections module provides an ABC Container class allowing you to know if a given object is a container or not. And what a surprise, a range object IS a container !

You might find it duck types like other containers.

[...]
>The docs at :
>https://docs.python.org/3.2/reference/datamodel.html#object.__contains__
>explains that a container is an object compatible with the membership test (in and not in operators).

Duck typing again: this bases the term on behaviour, not memory use.

>So a file is a container ? recall a file supports the in operator :

Yes and no. A file can be iterated. "in" on a file reads the file as a side 
effect of iterating over it. A generator also supports "in", again by 
iteration.

Neither of these things has a .__contains__ method; the "in" operator falls 
back to iteration if there is no .__contains__.

A container usually lets you test "in" in a nondestructive/nonconsuming 
fashion. An iterable can be "in"ed, but it will be consumed. So iterables are 
not, of themselves, containers.

So, range? A range object knows its bounds and state; it can answer "in" 
without consuming the range iteration, so it is effectively a container.

Hoping this helps.

Cheers,
Cameron Simpson <cs at zip.com.au>

[Alain] had been looking at his dashboard, and had not seen me, so I
ran into him. - Jean Alesi on his qualifying prang at Imola '93



More information about the Python-list mailing list