[issue44293] PEP 585 breaks inspect.isclass

Joseph Perez report at bugs.python.org
Thu Jun 3 03:46:14 EDT 2021


Joseph Perez <joperez at hotmail.fr> added the comment:

@Jelle Zijlstra Thank you for the explanation.

> The current implementation of GenericAlias has been around for a few releases by now, though, so that change might break some use cases.

I agree that a "fix" could have unexpected side-effect, my issue comes quite late indeed. By the way, Python typing is so much unstable (every version breaks the previous one), it's very complicated to write code that support multiple versions, so whatever the typing internal implementation, we must adapt.

> This is not true; it is the same for e.g. `set[int]`. Unless you meant something else here.

I have chosen `list[int]` as an example of `types.GenericAlias` introduced by PEP 585 (i could have chosen `set[int]` or `collections.abc.Collection[int]`). But other generic aliases, e.g. `typing.List[int]` or `MyClass[int]` (where `MyClass` inherits `Generic[T]`), are not instances of `type`.

> @Joseph Perez, is there a specific library or pattern that is broken by this?

Because `issubclass` requires a "class" as arg 1, I use the pattern `if isinstance(tp, type) and issubclass(tp, SomeClass)` (`isinstance` check being equivalent to `inspect.isclass`). With PEP 585, it breaks for `list[int]` and other builtin generic aliases.

> FWIW I did think rather carefully about which attributes to delegate or not, and delegating __class__ was intentional.

I don't have the context of the decision, so I can quite understand that delegating `__class__` was the right thing to do, especially when `__mro__` and other `type` attributes are also delegated. 
I mainly wanted to highlight this side effect, especially on the pattern mentioned above. (My issue title is a little bit excessive in this regard)

But as I've written, I've already so many wrappers to maintain compatibility between Python versions of typing that I can write a new one to handle this particularity of PEP 585. So this issue is not critical to me.

----------

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


More information about the Python-bugs-list mailing list