operator module isSequenceType with builtin set produces False

Terry Reedy tjreedy at udel.edu
Wed Dec 19 15:46:31 EST 2007


"MarkE" <mark.english at rbccm.com> wrote in message 
news:ad415199-ba3e-438d-88d0-1de9642f1018 at y5g2000hsf.googlegroups.com...
|| > Is there a short Pythonic way to determine whether an object is
| > iterable (iteratable ??)

Welcome to Python and its neat concept of iterables and iterators.
An iterable is an object that has an __iter__ method that returns an 
iterator.
An iterator is an object that has an __iter__ method that returns itself
and a next method that either returns another item or raises StopIteration.
(I omit an older alternative that will disappear in 3.0.  Ignore it.)
(Also, in 3.0, next methods will become __next__ methods.)
So iterators are also, intentionally, iterables.
So functions can take arguments that are either by beginning with
   it = iter(iterable)
without worrying about whether the iterable already is an iterator.
As Gabriel said, assume that an object returned by iter is an iterable.
Writing an __iter__ method that does not return such would be either a bug 
or a nasty trick.

I usually would not bother wrapping iter in a try: block.
Just iterate with 'it' and if it is not an iterator, you will find out.

| And here I probably meant container (although the url says sequence
| when the article meant container, bit like me):
| http://docs.python.org/ref/sequence-types.html
| "Containers usually are sequences (such as lists or tuples) or
| mappings (like dictionaries), but can represent other containers as
| well"

I think 'collection' is a better word that 'container' since 'container' 
implies an exclusivity (which is false) that 'collection' does not, at 
least not necessarily.

| So same question, but perhaps "isContainer()" rather than
| "isIterable()"

Python 3 will have Abstract Base Classes that will better defined some of 
these concepts.  So if class authors bother to inherit from them when 
appropriate, isinstance(obj, Sequence) or isinstance(obj, Number), for 
instance, will tell you.

Terry Jan Reedy






More information about the Python-list mailing list