Skip to content

Commit f369e4d

Browse files
committed
transformer: support unary literals
1 parent f713c87 commit f369e4d

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

basedtyping/transformer.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,9 @@ def _basedtyping(self, attr: str) -> ast.Attribute:
107107
)
108108
return ast.fix_missing_locations(result)
109109

110-
def _literal(self, value: ast.Constant | ast.Name | ast.Attribute) -> ast.Subscript:
110+
def _literal(
111+
self, value: ast.Constant | ast.Name | ast.Attribute | ast.UnaryOp
112+
) -> ast.Subscript:
111113
return self.subscript(self._typing("Literal"), value)
112114

113115
def subscript(self, value: ast.expr, slice_: ast.expr) -> ast.Subscript:
@@ -178,6 +180,14 @@ def visit_Constant(self, node: ast.Constant) -> ast.AST:
178180
return self._literal(node)
179181
return node
180182

183+
@override
184+
def visit_UnaryOp(self, node: ast.UnaryOp) -> ast.AST:
185+
if not isinstance(node.operand, ast.Constant):
186+
return node
187+
if not isinstance(node.op, (ast.UAdd, ast.USub)):
188+
return node
189+
return self._literal(node)
190+
181191
@override
182192
def visit_Tuple(self, node: ast.Tuple) -> ast.AST:
183193
with self.implicit_tuple(value=False):

tests/test_transformer.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,11 @@ def test_literal():
3131
validate("1 | 2", Union[Literal[1], Literal[2]])
3232

3333

34+
def test_negative():
35+
validate("-1", Literal[-1])
36+
validate("+1", Literal[1])
37+
38+
3439
def test_literal_union():
3540
validate("Union[1, 2]", Union[Literal[1], Literal[2]])
3641

0 commit comments

Comments
 (0)