Skip to content

Commit

Permalink
[Pyre] Handle type subscripts when applying annotations. (Instagram#335)
Browse files Browse the repository at this point in the history
* [Pyre] Handle type subscripts when applying annotations.

* Fix lint.

* Use matchers syntax instead of isinstance
  • Loading branch information
MaggieMoss authored Jul 14, 2020
1 parent 9d3bb11 commit 7219efc
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
5 changes: 4 additions & 1 deletion libcst/codemod/visitors/_apply_type_annotations.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from typing import Dict, List, Optional, Sequence, Set, Tuple, Union

import libcst as cst
from libcst import matchers as m
from libcst.codemod._context import CodemodContext
from libcst.codemod._visitor import ContextAwareTransformer
from libcst.codemod.visitors._add_imports import AddImportsVisitor
Expand Down Expand Up @@ -133,6 +134,8 @@ def _handle_Index(self, slice: cst.Index, node: cst.Subscript) -> cst.Subscript:

def _handle_Subscript(self, node: cst.Subscript) -> cst.Subscript:
slice = node.slice
if m.matches(node.value, m.Name(value="Type")):
return node
if isinstance(slice, list):
new_slice = []
for item in slice:
Expand Down Expand Up @@ -163,7 +166,7 @@ def _create_import_from_annotation(self, returns: cst.Annotation) -> cst.Annotat
return cst.Annotation(annotation=attr)
if isinstance(annotation, cst.Subscript):
value = annotation.value
if isinstance(value, cst.Name) and value.value == "Type":
if m.matches(value, m.Name(value="Type")):
return returns
return cst.Annotation(annotation=self._handle_Subscript(annotation))
else:
Expand Down
27 changes: 27 additions & 0 deletions libcst/codemod/visitors/tests/test_apply_type_annotations.py
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,33 @@ def foo() -> typing.Sequence[int]:
return []
""",
),
(
"""
from typing import Dict
example: Dict[str, Type[foo.Example]] = ...
""",
"""
from typing import Type
def foo() -> Type[foo.Example]:
class Example:
pass
return Example
example = { "test": foo() }
""",
"""
from typing import Dict, Type
def foo() -> Type[foo.Example]:
class Example:
pass
return Example
example: Dict[str, Type[foo.Example]] = { "test": foo() }
""",
),
)
)
def test_annotate_functions(self, stub: str, before: str, after: str) -> None:
Expand Down

0 comments on commit 7219efc

Please sign in to comment.