correct way to detect container type

Robin Becker robin at reportlab.com
Thu Oct 7 12:16:47 CEST 2004


Peter Otten wrote:

> 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
> 
lots of good ideas, but I think this breaks in 2.1 which we're still supporting. 
As do some of the iteration ideas.
-- 
Robin Becker



More information about the Python-list mailing list