isinstance()
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+) A question was asked about this at last night's PUG-meeting. The person was using the union option, but from Python v3.8. Sorting that out, he replaced the union with a list. No-go! Before correcting to a tuple... Why does the second argument need to be a tuple, given that any series of non-keyword arguments is a tuple; and that such a tuple will still need to be delimited by parentheses. In other words, other forms of delimiter/collection, eg list and set; being a series of elements/members would seem no different. Yes, the underlying C operation appears to only accept a single argument (am not C-soned, mea culpa!). There is some discussion about hashability, but isn't it coincidental rather than constructive? (again, maybe I've not understood...) Enquiring minds want to know... Web.Refs: https://docs.python.org/3/library/functions.html?highlight=isinstance#isinstance https://docs.python.org/3/c-api/object.html?highlight=isinstance#c.PyObject_IsInstance https://docs.python.org/3/reference/datamodel.html?highlight=isinstance -- Regards, =dn -- https://mail.python.org/mailman/listinfo/python-list
Re: isinstance()
On 03Aug2023 10:14, dn 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 -- https://mail.python.org/mailman/listinfo/python-list