correct way to detect container type

Carlos Ribeiro carribeiro at gmail.com
Thu Oct 7 07:08:31 EDT 2004


On Thu, 07 Oct 2004 11:16:47 +0100, Robin Becker <robin at reportlab.com> wrote:
> 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

In 2.1 you can probably use the __getitem__ test.

And I also think that you can define a conditional function in your
library, as to make possible for 2.2+ users to pass iterators. It's a
general solution, and more modern one at that.

I'm now using generators for related things -- namely, when generating
long output, I'm yielding individual strings for each line (or record)
instead of concatenating them into a huge string. Depending on the
system, it will make it more responsive. The performance impact is
negligible; in some scenarios, it's in fact faster, because you can
avoid lots of small string concatenations.

-- 
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: carribeiro at gmail.com
mail: carribeiro at yahoo.com



More information about the Python-list mailing list