Skip to content

Commit

Permalink
Generate annotations for NewType types (fixes #22) (#23)
Browse files Browse the repository at this point in the history
  • Loading branch information
folz authored and carljm committed Dec 16, 2017
1 parent 666b2a1 commit 2f682ef
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 1 deletion.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ htmlcov/
doc/_build
dist/
build/
.idea/
2 changes: 1 addition & 1 deletion CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ master
------

* Fix passing args to script run with ``monkeytype run`` (#18; merge of #21).

* Fix generated annotations for NewType types (#22; merge of #23).

17.12.1
-------
Expand Down
2 changes: 2 additions & 0 deletions monkeytype/stubs.py
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,8 @@ def render_annotation(anno: Any) -> str:
elem_type = _get_optional_elem(anno)
rendered = render_annotation(elem_type)
return 'Optional[' + rendered + ']'
elif hasattr(anno, '__supertype__'):
return anno.__name__
elif getattr(anno, '__module__', None) == 'typing':
return repr(anno).replace('typing.', '')
elif anno is NoneType:
Expand Down
12 changes: 12 additions & 0 deletions tests/test_stubs.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
Generator,
Iterator,
List,
NewType,
Optional,
Set,
Tuple,
Expand Down Expand Up @@ -42,6 +43,8 @@
from monkeytype.typing import NoneType
from .util import Dummy

UserId = NewType('UserId', int)


class TestImportMap:
def test_merge(self):
Expand Down Expand Up @@ -133,6 +136,10 @@ def has_length_exceeds_120_chars(
return None


def has_newtype_param(user_id: UserId) -> None:
pass


class TestHasUnparsableDefaults:
@pytest.mark.parametrize(
'func, expected',
Expand Down Expand Up @@ -241,6 +248,11 @@ def test_default_none_parameter_annotation(self):
expected = 'def test(x: Optional[int] = None) -> None: ...'
assert stub.render() == expected

def test_newtype_parameter_annotation(self):
stub = FunctionStub('test', inspect.signature(has_newtype_param), FunctionKind.MODULE)
expected = 'def test(user_id: UserId) -> None: ...'
assert stub.render() == expected


def _func_stub_from_callable(func: Callable, strip_modules: List[str] = None):
kind = FunctionKind.from_callable(func)
Expand Down

0 comments on commit 2f682ef

Please sign in to comment.