isinstance()

dn PythonList at DancesWithMice.info
Fri Aug 4 19:07:19 EDT 2023


On 03/08/2023 11.38, Jon Ribbens via Python-list wrote:
> On 2023-08-02, 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 following comment may hold a clue:
> 
>      if (PyTuple_Check(cls)) {
>          /* Not a general sequence -- that opens up the road to
>             recursion and stack overflow. */
> 
> https://github.com/python/cpython/blob/main/Objects/abstract.c#L2684
> 
> Plus an almost total lack of demand for change I should think.

Thanks for the reference!


Am not proposing a change (have learned 'the rule' and accepted 
life-as-it-is), but was curious about the restriction: why not any 
(reasonable sequence)?


Such pondering continues in my subversive mind, given such thoughts as:

- "we're all adults here"
(eg frequent justification when arguing about Python not having "private 
attributes" per-se).
So, if we introduce a complexity, on our own heads be it!
(hardly likely given that all we are likely to attempt is the 
application of a simple and short 'list' of [un]acceptable types).
NB understood that the quoted-code is applied in many and other 'scalar 
or tuple' situations.

- Python happily enables recursion, which "opens up the road to 
recursion and stack overflow.".
So, why install a 'nanny' to save us from ourselves here?
Again: seems on-the-surface that such 'lists' (at the code-line level) 
will be mono-dimensional 99.9% of the time.


NB having said that, the underlying mechanism *is* multi-dimensional: 
"direct, indirect, or virtual) subclass thereof" 
(https://docs.python.org/3/library/functions.html#isinstance)

Further: the 'rules' say: "classinfo is a tuple of type objects (or 
recursively, other such tuples)". Thus, can write:

 >>> target_object = ...
 >>> inner_tuple = float, complex
 >>> inner_tuple
(<class 'float'>, <class 'complex'>)
 >>> isinstance( target_object, ( str, inner_tuple, int, ), )
False

I can't say I've ever used such construction in-the-wild - either 
defining and then using an "inner_tuple", or even nesting. YMMV!


Any thoughts?

-- 
Regards,
=dn


More information about the Python-list mailing list