You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Narrow x is Sentinel where x is Union[type[Sentinel], ...] and Sentinel is @final #15553
Apply type narrowing in case of x is not C where x is of type Union[type[C], SomethingElse], from that union to SomethingElse in case when C is made final.
If C is final, then C is the only possible value that satisfies the type type[C]. So, if we compare identity, that means we can narrow the type in either direction.
Pitch
Empty class definitions are often used as sentinel values in a union, together with something else. These sentinel values can be made @final.
Consider this code:
fromtypingimportfinal, Union, Literal@finalclassSentinel:
passx: Union[type[Sentinel], int]
ifxisSentinel:
passelse:
# Should be `int`# But is: "Union[Type[x.Sentinel], builtins.int]"reveal_type(x)
Many libraries are doing that. A workaround that currently works is to use instantiated objects instead of types for sentinel values and narrow them by using an isinstance() check on the sentinel type, but that's far less clean, because for every sentinel we now have to deal with both the class and the instance.
changed the title [-]`is` based type narrowing of `x is (not) C` where x is `Union[type[C], ...]` and C is `@final`[/-][+]Narrow `x is Sentinel` where x is `Union[type[Sentinel], ...]` and Sentinel is `@final`[/+]on Jun 29, 2023
Activity
[-]`is` based type narrowing of `x is (not) C` where x is `Union[type[C], ...]` and C is `@final`[/-][+]Narrow `x is Sentinel` where x is `Union[type[Sentinel], ...]` and Sentinel is `@final`[/+]sobolevn commentedon Jul 12, 2023
I have a prototype ready :)
jonathanslenders commentedon Aug 7, 2023
Thank you @sobolevn!
Narrowing for final type objects (python#20661)