[Python-ideas] Allow isinstance second argument to be a set of types

Alexander Belopolsky alexander.belopolsky at gmail.com
Wed Jul 6 20:01:28 CEST 2011


On Tue, Jul 5, 2011 at 6:36 PM, Guido van Rossum <guido at python.org> wrote:
> FWIW, the restriction to tuples is to avoid burdening the recursive C code
> with checks for cycles. Please keep that property.

Keeping this property does not seem that hard: preserve the current
behavior when classinfo is a type or a tuple and return
any(_isinstance(object, type) for type in classinfo) for any other
type of classinfo. (In the last expression, "_isinstance" accepts only
types for the second argument.)

It looks like in this discussion a useful feature is held hostage to
an exotic corner case.  I understand that it may sometimes be useful
to write isinstance(x, (MyString, StringTypes)), but

   isinstance(x, (MyString,)+StringTypes)

is just as readable.  Furthermore, with str/unicode unification and
addition of ABCs in py3k, I would expect nested classinfo to become
even less useful.

Note that the current error message from isinstance() does not mention
a possibility of nested tuples:

>>> isinstance(1, [int])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: isinstance() arg 2 must be a type or tuple of types

Since no one has ever complained about this, I conclude that people
rightfully consider nested tuple classinfo to be too exotic to mention
in an error message.

I don't see any problem with restricting recursive behavior to tuples.
 It is often recommended that lists be used for homogeneous
collections and tuples for mixed-type collections.  This rule will
naturally lead users to choose tuples when they need a nested
collection.  On the other hand, some users may find isinstance(x,
[int, float]) or isinstance(x, {int, float}) more readable than
isinstance(x, (int, float)) either simply because [] or {} stand out
better in the argument list or because they are used to seeing
homogeneous collections displayed as lists.



More information about the Python-ideas mailing list