correct way to detect container type

Peter Otten __peter__ at web.de
Thu Oct 7 11:50:22 CEST 2004


Robin Becker wrote:

> I seem often to allow list/tuple arguments to be a singleton. This leads
> to code of the form
> 
> if type(arg) not in (type(()),type([])): arg = [arg]
> 
> 
> or alternatively
> 
> from type import ListType, TupleType
> _seqTypes = ListType, TupleType
> ......
> if type(arg) not in _seqTypes: ....
> 
> is there a 'best' way to do this?

I prefer 

isinstance(var, (list, tuple))

to the above, but I don't think there is one correct way. Often you don't
want a full-blown container, just an iterable. Then

try:
    it = iter(var)
except TypeError:
    it = iter([var])

may be more appropriate. However, you will end up iterating over the
characters if var is a string, which often has to be guarded against with
an additional isinstance(basestring) test

try:
    iter(var)
except TypeError:
    var = [var]
else:
    if isinstance(var, basestring): var = [var]

Peter




More information about the Python-list mailing list