Skip to content

How to use Literal #1396

Answered by erictraut
elbaro asked this question in Q&A
Jan 20, 2021 · 2 comments · 1 reply
Discussion options

You must be logged in to vote

There are a few problems here. First, the expression Literal["A", "B"] is shorthand for Union[Literal["A"], Literal["B"]], and you cannot use union types in a NewType call. Pyright should generate an error in this circumstance.

Second, even if you remove the NewType and simplify the Literal, you cannot instantiate it because a literal is an object, not a class. So Pyright should generate an error for the expression Literal["A"]("A").

The correct way to use literals is in a type annotation like this:

LetterGrade = Literal["A", "B", "C", "D"]
def foo(grade: LetterGrade):
    print(grade)

foo("A") # Allowed
foo("F") # Generates error

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Answer selected by elbaro
Comment options

You must be logged in to vote
1 reply
@erictraut
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants