-
from typing import NewType, Literal
ABC = NewType('ABC', Literal['A', 'B'])
var = ABC('XYZ') Hi, I am new to python typing.
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
There are a few problems here. First, the expression Second, even if you remove the 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 |
Beta Was this translation helpful? Give feedback.
-
I actually want This is the hack that worked for me. from typing import TYPE_CHECKING, NewType, Literal
def ABCNewType(name, tp):
def new_type(x: Literal['A', 'B', 'C']):
print('this should not run in runtime')
return x
new_type.__name__ = name
new_type.__supertype__ = tp
return new_type
print('TYPE_CHECKING', TYPE_CHECKING)
if TYPE_CHECKING: # this is evaluated once in runtime
ABC = ABCNewType('ABC', str)
else:
ABC = NewType('ABC', str)
a = ABC('x') 20:9 - error: Argument of type "Literal['a']" cannot be assigned to parameter "x" of type "Literal['A', 'B', 'C']" in function "new_type"
Type "Literal['a']" cannot be assigned to type "Literal['A', 'B', 'C']"
"Literal['a']" cannot be assigned to type "Literal['A']"
"Literal['a']" cannot be assigned to type "Literal['B']"
"Literal['a']" cannot be assigned to type "Literal['C']" (reportGeneralTypeIssues)
1 error, 0 warnings, 0 infos
Completed in 0.482sec |
Beta Was this translation helpful? Give feedback.
There are a few problems here. First, the expression
Literal["A", "B"]
is shorthand forUnion[Literal["A"], Literal["B"]]
, and you cannot use union types in aNewType
call. Pyright should generate an error in this circumstance.Second, even if you remove the
NewType
and simplify theLiteral
, you cannot instantiate it because a literal is an object, not a class. So Pyright should generate an error for the expressionLiteral["A"]("A")
.The correct way to use literals is in a type annotation like this: