[issue39550] isinstance accepts subtypes of tuples as second argument

Paul Ganssle report at bugs.python.org
Tue Feb 4 14:49:31 EST 2020


Paul Ganssle <p.ganssle at gmail.com> added the comment:

Serhiy: I think at least a test for this particular corner case should be added, so that no implementations of `isinstance` that use the CPython test suite hit an infinite recursion in that event, I guess?

Though I think it's maybe an open question as to what the correct behavior is. Should we throw on any tuple subclass because there's no reason to support tuple subclasses? Should we switch to using __iter__ when it's defined because there are other cases where the custom behavior of the subclass is defined by its __iter__? Should we make it a guarantee that __iter__ is *never* called?

I can't really think of a reason why defining __iter__ on a tuple subclass would be anything other than a weird hack, so I would probably say either ban tuple subclasses or add a test like so:

def testIsinstanceIterNeverCalled(self):
    """Guarantee that __iter__ is never called when isinstance is invoked"""
    class NoIterTuple(tuple):
        def __iter__(self):  # pragma: nocover
            raise NotImplemented("Cannot call __iter__ on this.")

    self.assertTrue(isinstance(1, NoIterTuple((int,))))

----------
nosy: +p-ganssle

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue39550>
_______________________________________


More information about the Python-bugs-list mailing list