isinstance()

Cameron Simpson cs at cskk.id.au
Wed Aug 2 21:14:35 EDT 2023


On 03Aug2023 10:14, dn <PythonList at DancesWithMice.info> wrote:
>Can you please explain why a multi-part second-argument must be a 
>tuple and not any other form of collection-type?
>
>The signature is: isinstance(object, classinfo)
>leading to "classinfo" of:
>
>1/ a single class/type, eg int
>2/ a tuple of same, eg ( int, str, )
>3/ a union type, eg int | str (v3.10+)

help(isinstance) (in 3.8) says class_or_tuple.

I would speculate that requiring a tuple has two advantages:
- it may lend itself to promotion to a set for comparison with the MRO 
   of object (IIRC the "foo in (a,b,c)" is optimised this way also), and 
   this in turn may hint at the Hashable requirement
- it is _frugal_ in what we expect there, leaving open a future meaning 
   for something else in that place (for example, isinstance well 
   predates type annotations, and a looser kind of argument might have 
   precluded this new usage)

There's similar language in this try/except documentation:
file:///Users/cameron/var/doc/python/3.8.0/reference/compound_stmts.html#index-10

      For an except clause with an expression, that expression is 
      evaluated, and the clause matches the exception if the resulting 
      object is “compatible” with the exception. An object is compatible 
      with an exception if it is the class or a base class of the 
      exception object or a tuple containing an item compatible with the 
      exception.

To my mind the tuple requirement lends itself to a distinct syntax (the 
brackets) and frugal use of the meaning of what values can occur there.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Python-list mailing list