detecting variable types

Alex Martelli aleaxit at yahoo.com
Thu Sep 23 00:05:14 CEST 2004


Andrew Koenig <ark at acm.org> wrote:
   ...
> I don't see anything particularly wrong with detecting the type this way:
> 
>     if isinstance(params[key1], list):

Better than checking type(...), but then, a lesser evil need not be
'right'.

> Of course that won't work for other kinds of sequences, but if that's what
> you want, then that's what you want.

Sometimes people want what's not best for them, and sometimes they
believe they want something, but really don't.  If somebody asks me
about how best to shoot his own foot, I may perhaps suggest weapon types
and suitable ammunition, but often I'd add some note about the problems
that often result by shooting one's own foot, even with the most
suitable choice of ammunition and weapon.  ((Come on -- if somebody
asked __in a C++ group__ how best to code the equivalent of...:

    if(is_circle(x)) draw_circle(x);
    else if(is_square(x)) draw_square(x);
    ...
would you just mention how dynamic_cast may be used for the purpose,
without one word as to how a polymorphic x.draw() is better...?-))

Nevertheless, singling out _strings_ from other kinds of sequences and
iterables IS unfortunately needed sometimes.  That's why built-in type
basestring exists: for the sole reason of allowing a typetest of the
form "if isinstance(whatever, basestring):...".  Once strings (byte and
unicode kinds) are out of the way, all other sequences and iterables can
often be treated uniformly and polymorphically with a for loop or
whatever.  A frequent idiom:

   if isinstance(whatever, basestring):
       whatever = [whatever]
   try: whatever = iter(whatever)
   except TypeError: whatever = iter([whatever])
   for item in whatever:
      ...

this deals sensibly with being passed any iterable (singling out strings
as scalars even though they're iterable) OR any non-iterable (to be
treated as the equivalent singleton-iterable with that one item only).


Alex



More information about the Python-list mailing list