ilevkivskyi / typing_inspect

Runtime inspection utilities for Python typing module
MIT License
350 stars 35 forks source link

is_literal broken with new typing_extensions #100

Closed sanderr closed 1 year ago

sanderr commented 1 year ago

typing_inspect.is_literal is broken when typing-extensions-4.6.0 is installed. The following simple check fails. Installing typing-extensions-4.5.0 makes it work.

import typing
import typing_inspect

assert typing_inspect.is_literal_type(typing.Literal)  # this fails on Python 3.9.15 with typing_extensions==4.6.0

While typing_extensions made some changes in their latest release I believe it didn't introduce any backwards incompatible changes and I would argue the cause is a bug in typing_inspect. It seems to count on typing.Literal and typing_extensions.Literal being the same. It imports Literal from typing_extensions (here) and uses that for the is_literal check (here). As far as I can figure out this assumption is unfounded as it was never documented that the two types would be the same, they just happened to be so for a while.

typing-extensions-4.6.0 was released earlier today. According to its changelog it includes a bugfix on typing_extensions.Literal. Indeed, while on typing-extensions-4.5.0 typing.Literal is typing_extensions.Literal this is no longer the case for the new version. As far as I can tell they did not introduce any backwards incompatible changes.

I tested this on Python 3.9.15. The issue does not seem to be present on 3.10.10, there typing.Literal is typing_extensions.Literal still holds.

EDIT: shifted the text around a bit in an effort to make it more readable

sanderr commented 1 year ago

Pydantic seems to have a similar check, potentially relevant discussion at https://github.com/pydantic/pydantic/issues/5821#issuecomment-1558520974

AlexWaygood commented 1 year ago

You'll probably want a fix similar to https://github.com/pydantic/pydantic/pull/5826

ilevkivskyi commented 1 year ago

Yeah. I will make a PR soon.