[issue45438] inspect not capturing type annotations created by __class_getitem__

Guido van Rossum report at bugs.python.org
Mon Oct 25 15:16:37 EDT 2021


Guido van Rossum <guido at python.org> added the comment:

> The issue is that this feature is internally inconsistent (isinstance() is not consistent with issubclass()),

issubclass(x, list[int]) rejects the second argument for reasons explained in the PEP. I don't think from that reasoning you can infer that list[int] is not a type. Rather the contrary -- if it's not a type the PEP could just have said "it's not a type" but it doesn't, it says "it's unacceptable as second arg to issubclass()". In fact, the PEP uses language ("instances of parameterized collections") that makes me think in the PEP author's mind list[int] *is* a type.

> the C implementation of list[int] is not consistent with the Python implementation of List[int],

Consistency with typing was not a goal of the PEP.

> and a lot of code was not tested with this feature,

What other places are there that are broken because of this?

> so we perhaps have a lot of bugs in the stdlib and in the third-party libraries.

Without more evidence this sounds like speculation. *With* evidence you might well convince me.

> Are we going to backport changes for making code working with GenericAlias as a type to 3.9 and 3.10?

I'm fine with backporting the fix in the PR, GH-29212.

> If not, we will actually add new features in 3.11 and keep 3.9 and 3.10 broken. If yes, these changes can have larger effect than just making isinstance(list[int], type) returning False, and they can break more code.

Are there other fixes you already know about besides GH-29212? That PR seems 100% beneficial.

> Note also that isinstance(List[int], type) was True before 3.7, and we intentionally made it False in 3.7 (it was required significant rewriting of the typing module and introducing __mro_entries__). Do we want to revert this decision?

I don't recall why we changed that, I thought it was a side effect of making the implementation faster, not because of a decision that we didn't want these to be treated as types. I looked at inspect.py in 3.6, and it seems its formatannotation() has a special case for annotations that come from the typing module (like List[int]). I guess nobody thought to have a test for that, so the bug in inspect.py slipped by when it was introduced in 3.9 -- we're relying on Raymond's keen eye here. But if we had had such a test, and it had alerted us to the problem in 3.9 when types.GenericAlias was introduced, I expect that we would have fixed it just like martinitus does in his PR.

Anyway, I am willing to be swayed by evidence, but this bug in inspect.py isn't enough.

----------

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


More information about the Python-bugs-list mailing list