Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support PEP-604 style unions in decorator annotations #429

Merged
merged 1 commit into from
Dec 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion libcst/matchers/_visitors.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,18 @@ def _get_possible_match_classes(matcher: BaseMatcherNode) -> List[Type[cst.CSTNo
return [getattr(cst, matcher.__class__.__name__)]


def _get_possible_annotated_classes(annotation: object) -> List[Type[object]]:
def _annotation_looks_like_union(annotation: object) -> bool:
if getattr(annotation, "__origin__", None) is Union:
return True
# support PEP-604 style unions introduced in Python 3.10
return (
annotation.__class__.__name__ == "Union"
and annotation.__class__.__module__ == "types"
)


def _get_possible_annotated_classes(annotation: object) -> List[Type[object]]:
if _annotation_looks_like_union(annotation):
return getattr(annotation, "__args__", [])
else:
return [cast(Type[object], annotation)]
Expand Down
23 changes: 23 additions & 0 deletions libcst/matchers/tests/test_decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from ast import literal_eval
from textwrap import dedent
from typing import List, Set
from unittest.mock import Mock

import libcst as cst
import libcst.matchers as m
Expand Down Expand Up @@ -993,3 +994,25 @@ def bar() -> None:

# We should have only visited a select number of nodes.
self.assertEqual(visitor.visits, ['"baz"'])


# This is meant to simulate `cst.ImportFrom | cst.RemovalSentinel` in py3.10
FakeUnionClass: Mock = Mock()
setattr(FakeUnionClass, "__name__", "Union")
setattr(FakeUnionClass, "__module__", "types")
FakeUnion: Mock = Mock()
FakeUnion.__class__ = FakeUnionClass
FakeUnion.__args__ = [cst.ImportFrom, cst.RemovalSentinel]


class MatchersUnionDecoratorsTest(UnitTest):
def test_init_with_new_union_annotation(self) -> None:
class TransformerWithUnionReturnAnnotation(m.MatcherDecoratableTransformer):
@m.leave(m.ImportFrom(module=m.Name(value="typing")))
def test(
self, original_node: cst.ImportFrom, updated_node: cst.ImportFrom
) -> FakeUnion:
pass

# assert that init (specifically _check_types on return annotation) passes
TransformerWithUnionReturnAnnotation()