Narrow x is Sentinel
where x is Union[type[Sentinel], ...]
and Sentinel is @final
#15553
Labels
x is Sentinel
where x is Union[type[Sentinel], ...]
and Sentinel is @final
#15553
Feature
Apply type narrowing in case of
x is not C
wherex
is of typeUnion[type[C], SomethingElse]
, from that union toSomethingElse
in case whenC
is madefinal
.If
C
is final, thenC
is the only possible value that satisfies the typetype[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:
An example can be found in the
h11
library:https://github.com/python-hyper/h11/blob/cdccbeff44a39426b58010eb454a75015ec6f8bc/h11/_connection.py#L426
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.The text was updated successfully, but these errors were encountered: