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
Improve error messages related to literal types (#6149)
This pull request improves how we handle error messages with Literal types in
three different ways:
1. When the user tries constructing types like `Literal[3 + a]`, we now report
an error message that says 'Invalid type: Literal[...] cannot contain
arbitrary expressions'.
2. We no longer recommend using Literal[...] when doing `A = NewType('A', 4)`
or `T = TypeVar('T', bound=4)`. This resolves#5989.
(The former suggestion is a bad one: you can't create a NewType of a
Literal[...] type. The latter suggestion is a valid but stupid one:
`T = TypeVar('T', bound=Literal[4])` is basically the same thing as
`T = Literal[4]`.)
3. When the user tries using complex numbers inside Literals (e.g.
`Literal[3j]`), we now report an error message that says 'Parameter 1
of Literal[...] cannot be of type "complex"'. This is the same kind of
error message we previously used to report when the user tried using
floats inside of literals.
In order to accomplish bullet point 1, moved the "invalid type comment or
annotation" checks from the parsing layer to the semantic analysis layer.
This lets us customize which error message we report depending on whether
or not the invalid type appears in the context of a Literal[...] type.
In order to accomplish this, I repurposed RawLiteralType so it can represent
any arbitrary expression that does not convert directly into a type (and
renamed 'RawLiteralType' to 'RawExpressionType' to better reflect this new
usage). I also added an optional "note" field to that class: this lets the
parsing layer attach some extra context that would be difficult to obtain up
in the semantic analysis layer.
In order to accomplish bullet point 2, I modified the type analyzer so that
the caller can optionally suppress the error messages that would otherwise be
generated when a RawExpressionType appears outside of a Literal context.
Bullet point 3 only required a minor tweak to the parsing and error handling
code.
0 commit comments