Skip to content

Commit

Permalink
Handle missing branches in BinOp (#392)
Browse files Browse the repository at this point in the history
Co-authored-by: Alex Grönholm <alex.gronholm@nextday.fi>
  • Loading branch information
vthemelis and agronholm committed Sep 3, 2023
1 parent 0c118de commit 041b0e3
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
5 changes: 5 additions & 0 deletions docs/versionhistory.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@ Version history

This library adheres to `Semantic Versioning 2.0 <https://semver.org/#semantic-versioning-200>`_.

**UNRELEASED**

- Fixed ``AttributeError`` where the transformer removed elements from a PEP 604 union
(`#384 <https://github.com/agronholm/typeguard/issues/384>`_)

**4.1.3** (2023-08-27)

- Dropped Python 3.7 support
Expand Down
10 changes: 10 additions & 0 deletions src/typeguard/_transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,16 @@ def visit_BinOp(self, node: BinOp) -> Any:
self.generic_visit(node)

if isinstance(node.op, BitOr):
# If either branch of the BinOp has been transformed to `None`
# then the `ast.generic_visit` will eliminate that branch completely.
# If this happens, treat the BinOp as just the other branch.
if not hasattr(node, "left") and not hasattr(node, "right"):
return None
elif not hasattr(node, "left"):
return node.right
elif not hasattr(node, "right"):
return node.left

# Return Any if either side is Any
if self._memo.name_matches(node.left, *anytype_names):
return node.left
Expand Down
31 changes: 31 additions & 0 deletions tests/test_transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -1570,6 +1570,37 @@ def foo(x: str) -> None:
)


def test_union_annotation_with_or_operator() -> None:
node = parse(
dedent(
"""
from __future__ import annotations
class A:
...
def foo(A: A | None) -> None:
pass
"""
)
)
TypeguardTransformer(["foo"]).visit(node)
assert (
unparse(node)
== dedent(
"""
from __future__ import annotations
def foo(A: A | None) -> None:
from typeguard import TypeCheckMemo
from typeguard._functions import check_argument_types
memo = TypeCheckMemo(globals(), locals())
check_argument_types('foo', {'A': (A, None)}, memo)
"""
).strip()
)


def test_dont_parse_annotated_2nd_arg() -> None:
# Regression test for #352
node = parse(
Expand Down

0 comments on commit 041b0e3

Please sign in to comment.