Proper Way of checking for a collections class

Robert Brewer fumanchu at amor.org
Thu Apr 22 13:37:15 EDT 2004


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




More information about the Python-list mailing list