Skip to content

bpo-37838: get_type_hints for wrapped functions with forward reference #17126

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

Merged
merged 5 commits into from
Nov 21, 2019
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
7 changes: 7 additions & 0 deletions Lib/test/ann_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"""

from typing import Optional
from functools import wraps

__annotations__[1] = 2

Expand Down Expand Up @@ -51,3 +52,9 @@ def foo(x: int = 10):
def bar(y: List[str]):
x: str = 'yes'
bar()

def dec(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
15 changes: 15 additions & 0 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2778,6 +2778,16 @@ async def g_with(am: AsyncContextManager[int]):

gth = get_type_hints

class ForRefExample:
@ann_module.dec
def func(self: 'ForRefExample'):
pass

@ann_module.dec
@ann_module.dec
def nested(self: 'ForRefExample'):
pass


class GetTypeHintTests(BaseTestCase):
def test_get_type_hints_from_various_objects(self):
Expand Down Expand Up @@ -2876,6 +2886,11 @@ def test_get_type_hints_ClassVar(self):
'x': ClassVar[Optional[B]]})
self.assertEqual(gth(G), {'lst': ClassVar[List[T]]})

def test_get_type_hints_wrapped_decoratored_func(self):
expects = {'self': ForRefExample}
self.assertEqual(gth(ForRefExample.func), expects)
self.assertEqual(gth(ForRefExample.nested), expects)


class GetUtilitiesTestCase(TestCase):
def test_get_origin(self):
Expand Down
6 changes: 5 additions & 1 deletion Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1234,7 +1234,11 @@ def get_type_hints(obj, globalns=None, localns=None):
if isinstance(obj, types.ModuleType):
globalns = obj.__dict__
else:
globalns = getattr(obj, '__globals__', {})
nsobj = obj
# Find globalns for the unwrapped object.
while hasattr(nsobj, '__wrapped__'):
nsobj = nsobj.__wrapped__
globalns = getattr(nsobj, '__globals__', {})
if localns is None:
localns = globalns
elif localns is None:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
:meth:`typing.get_type_hints` properly handles functions decorated with :meth:`functools.wraps`.