Skip to content

Commit

Permalink
Fixed test failures on Python 3.7
Browse files Browse the repository at this point in the history
  • Loading branch information
agronholm committed Mar 20, 2023
1 parent 2a3376e commit 2aca41d
Showing 1 changed file with 17 additions and 9 deletions.
26 changes: 17 additions & 9 deletions src/typeguard/_transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,17 +367,25 @@ def _convert_annotation(self, annotation: expr) -> expr:
def _convert_annotation(self, annotation: expr | None) -> expr | None:
# Parse forward references to AST nodes, and convert PEP 604 unions to
# typing.Unions on Pythons older than 3.9
if isinstance(annotation, Constant) and isinstance(annotation.value, str):
expression = ast.parse(annotation.value, mode="eval")
if isinstance(annotation, (Constant, Str)):
# An explicit forward reference is ast.Str on Python 3.7, Constant on later
# versions
if isinstance(annotation, Str):
value = annotation.s
else:
value = annotation.value

# Convert each PEP 604 unions (x | y) to a typing.Union
if UnionTransformer is not None and any(
isinstance(node, BinOp) for node in walk(expression)
):
union_name = self._memo.get_import("typing", "Union")
expression = UnionTransformer(union_name).visit(expression)
if isinstance(value, str):
expression = ast.parse(value, mode="eval")

# Convert each PEP 604 unions (x | y) to a typing.Union
if UnionTransformer is not None and any(
isinstance(node, BinOp) for node in walk(expression)
):
union_name = self._memo.get_import("typing", "Union")
expression = UnionTransformer(union_name).visit(expression)

annotation = ast.copy_location(expression.body, annotation)
annotation = ast.copy_location(expression.body, annotation)

# Store names used in the annotation
if annotation:
Expand Down

0 comments on commit 2aca41d

Please sign in to comment.