Proper Way of checking for a collections class

Yermat loic at yermat.net1.nerim.net
Thu Apr 22 15:11:41 EDT 2004


Robert Brewer a écrit :

> Gary Coulbourne wrote:
> 
>>I've been trying to find a good idiom for testing if the input to a
>>function is one of the collections classes... the best I 
>>could do is this:
>>
>>if hasattr(thing_to_test, '__iter__'):
>>    ...
> 
> 
> The best way depends upon (and mirrors) exactly what you want to do with
> those classes. If you're going to call iter(thing), then the above is
> fine. If instead you want sequences, try operator.isSequenceType,
> etcetera.
> 
> 
> FuManChu
> 

I don't think so ! For example, String has no __iter__ method but is 
iterable !
I would do :

try:
     it = iter(thing_to_test)
except TypeError:
     it = None

if it:
     for var in it:
         do stuff...

-- 
Yermat




More information about the Python-list mailing list