disgrating a list

Bryan Olson fakeaddress at nowhere.org
Sat Sep 2 14:45:42 EDT 2006


Tal Einat wrote:
> Tim Chase wrote:
>> I'm not sure if '__iter__' is the right thing to be looking for,
>> but it seems to work at least for lists, sets, dictionarys (via
>> their keys), etc.  I would use it because at least then you know
>> you can iterate over it
> 
> AFAIK and as seen throughout posts on c.l.py, the best way to check if
> something is iterable is:
> 
> try:
>     iter(obj)
> except TypeError:
>     <obj is not iterable>
> else:
>     <obj is iterable>

It's a trap: there's no good general Pythonic flatten().

In Tim's version flatten(['hello', [['world']]]) is
['hello', 'world']. With the try...except above, it comes
out ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
That's not usually what people want.

It's not just a string problem. Flattening arbitrary
sequences of Foo-like things assumes that no one
implements objects that are both Foos and sequences.
Duck-typing lets you treat lots of types of things
polymorphically, but it breaks the partitioning by
kind that flatten() requires.

Fortunately there's no real need for a general flatten().


-- 
--Bryan



More information about the Python-list mailing list