Possible regression in enum member literals as sentinel values #8820
-
A pattern I've seen somewhat often (for example in attrs) and have adopted myself in a couple projects is declaring sentinel values as follows: import enum
import typing
class _Sentinel(enum.Enum):
SENTINEL = enum.auto()
SENTINEL = _Sentinel.SENTINEL
def foo(x: int | None | typing.Literal[SENTINEL] = SENTINEL):
... where the line with
I am aware that this can still be achieved by changing the annotation to def foo(x: int | None | _Sentinel = SENTINEL):
...
# OR
def foo(x: int | None | typing.Literal[_Sentinel.SENTINEL] = SENTINEL):
... However, with attrs as an example, this would lead to accessing My "question" therefore is whether or not the typing errors raised in the first codeblock are intentional.
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Yes, this error is intentional. This behavior is mandated by the Python typing spec, which explicitly disallows variables from being used in type expressions, including Your code sample is conflating value expressions with type expressions. The statement |
Beta Was this translation helpful? Give feedback.
Yes, this error is intentional. This behavior is mandated by the Python typing spec, which explicitly disallows variables from being used in type expressions, including
Literal
type definitions.Your code sample is conflating value expressions with type expressions. The statement
SENTINEL = _Sentinel.SENTINEL
defines a variable whose type is initialized to the value_Sentinel.SENTINEL
. By contrast, the statementstype SENTINEL = Literal[_Sentinel.SENTINEL]
andSENTINEL: TypeAlias = Literal[_Sentinel.SENTINEL]
define a type alias whose type is a literal.