[Python-Dev] Need a way to test for 8-bit-or-unicode-string

Guido van Rossum guido@python.org
Fri, 05 Oct 2001 11:43:44 -0400


>     GvR> if isinstance(x, str) or isinstance(x, unicode): > > is
>     GvR> apparently too much typing.
> 
>     NS> Perhaps we could extend isinstance().  How about
> 
>     NS>     isinstance(x, str, unicode)
> 
>     NS> or
> 
>     NS>     isinstance(x, (str, unicode))
> 
>     NS> This is a common problem not limited to string types.  I often
>     NS> want to test if something is a tuple or a list for example.
> 
> That's an interesting idea, but please use the former signature, not
> the latter.

Why?  The varargs signature makes it less convenient (and less
efficient!) to pre-calculate the list of types.  It also makes it
harder to implement this in PyObject_IsInstance(), so that C code can
use this convenience.  Finally, if I already know the meaning of
isinstance(x, y), then when I encounter isinstance(x, (y, z)) for the
first time, it's very easy to guess the meaning.  The meaning of
isinstance(x, y, z) is much more murky: z could be an optional
argument specifying some other modification of the basic isinstance().

> And what would it return?  It needs to return a true value on success,
> but maybe instead of returning 1, it might be more useful to return
> the type argument that matched, e.g.:
> 
> >>> isinstance('', str, unicode)
> <type 'str'>
> >>> isinstance(u'', str, unicode)
> <type 'unicode'>
> >>> isinstance((), list, dictionary, tuple)
> <type 'tuple'>
> >>> isinstance(7, list, dictionary, tuple)
> 0

Here I agree with Fred: too much hackery combined in one function.
And what's the use case?

--Guido van Rossum (home page: http://www.python.org/~guido/)