Skip to content

gh-85403: Make wraps retain type annotations #21392

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

Closed
wants to merge 4 commits into from
Closed
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
17 changes: 17 additions & 0 deletions Doc/library/functools.rst
Original file line number Diff line number Diff line change
Expand Up @@ -647,6 +647,23 @@ The :mod:`functools` module defines the following functions:
on the wrapper function). :exc:`AttributeError` is still raised if the
wrapper function itself is missing any attributes named in *updated*.

When assigning the ``__annotations__`` attribute (when it's part of the
``assigned`` list parameter), it will be populated only if missing some
Comment on lines +650 to +651
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it not part of WRAPPER_ASSIGNMENTS?

annotations as follows:

* If the wrapper function defines it's own return type and parameter
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* If the wrapper function defines it's own return type and parameter
* If the wrapper function defines its own return type and parameter

annotations, those will be preserved.
Comment on lines +654 to +655
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is not very clear from this paragraph what this actually does.

Suppose the wrapper has annotations for 'x' and 'y' and the wrapped function has annotations for 'z'. Does 'z' get added to the wrapper's annotations?

Suppose the wrapper has no annotations, so it receives annotations for 'x', 'y' and 'z' from the wrapped function. What happens if the wrapper doesn't have arguments by those names? That is going to be confusing in some cases of further introspection.

It almost sounds like __annotations__ should be listed under updated instead of assigned, there are so many special cases.


* If the wrapper function does not annotate the return type, it will be
copied from the wrapped if any.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
copied from the wrapped if any.
copied from the wrapped function, if it specifies a return type.


* If the wrapped function does not annotate any parameters, the annotations
for them will be copied over from the wrapped if any.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
for them will be copied over from the wrapped if any.
for them will be copied over from the wrapped function, if it has any.


That ensures that any custom annotations from the wrapper will not be
overridden by the wrapped, allowing to change the annotated types of
the wrapped function.

.. versionadded:: 3.2
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clearly you need a versionadded:: 3.12 block for the new treatment of __annotations__.

Automatic addition of the ``__wrapped__`` attribute.

Expand Down
31 changes: 31 additions & 0 deletions Lib/functools.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,45 @@ def update_wrapper(wrapper,
updated is a tuple naming the attributes of the wrapper that
are updated with the corresponding attribute from the wrapped
function (defaults to functools.WRAPPER_UPDATES)

There's a special treatment for the `__annotations__` attribute:
* If the wrapper defines a return type, then that will be used, if not,
the one from the wrapped function will be used if any.
* If the wrapper defines any parameter types, those will be used, if
not, the ones from the wrapped function will be used if any.
"""
for attr in assigned:
try:
value = getattr(wrapped, attr)
except AttributeError:
pass
else:
if attr == '__annotations__':
continue
setattr(wrapper, attr, value)

if '__annotations__' in assigned:
try:
# Issue #41231: copy the annotations from wrapped, only if they are
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Update the bug number using the GH-NNN or bpo-NNN format.

# not already defined in the wrapper
if not wrapper.__annotations__:
wrapper.__annotations__ = wrapped.__annotations__
# if the wrapper does not annotate the parameters, copy their
# annotations over from the wrapped
elif ('return' in wrapper.__annotations__
and len(wrapper.__annotations__) == 1):
wrapper.__annotations__ = {
**wrapped.__annotations__,
**wrapper.__annotations__,
}
# if the wrapper does not annotate the return type, copy the
# annotation from the wrapped
elif ('return' not in wrapper.__annotations__
and 'return' in wrapped.__annotations__):
wrapper.__annotations__['return'] = wrapped.__annotations__['return']
Comment on lines +80 to +84
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh this is quite different from what I had understood from the docs (which I read before reading the code). I recommend changing the docs to more clearly describe what this does.

except AttributeError:
pass

for attr in updated:
getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
# Issue #17482: set __wrapped__ last so we don't inadvertently copy it
Expand Down
18 changes: 18 additions & 0 deletions Lib/test/ann_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,22 @@ def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper

def dec_with_return_type(func):
@wraps(func)
def wrapper(*args, **kwargs) -> bool:
return bool(func(*args, **kwargs))
return wrapper

def dec_with_arg_types(func):
@wraps(func)
def wrapper(self, custom_arg: int, *args, **kwargs):
return func(self, custom_arg, *args, **kwargs)
return wrapper

def dec_with_args_and_return_types(func):
@wraps(func)
def wrapper(self, custom_arg: int, *args, **kwargs) -> bool:
return bool(func(self, custom_arg, *args, **kwargs))
return wrapper

u: int | float
23 changes: 17 additions & 6 deletions Lib/test/test_functools.py
Original file line number Diff line number Diff line change
Expand Up @@ -599,10 +599,17 @@ class TestUpdateWrapper(unittest.TestCase):

def check_wrapper(self, wrapper, wrapped,
assigned=functools.WRAPPER_ASSIGNMENTS,
updated=functools.WRAPPER_UPDATES):
updated=functools.WRAPPER_UPDATES,
expected_annotations=None,
):
# Check attributes were assigned
for name in assigned:
self.assertIs(getattr(wrapper, name), getattr(wrapped, name))
if expected_annotations is not None and name == '__annotations__':
self.assertEqual(expected_annotations, wrapper.__annotations__)
elif name == '__annotations__':
self.assertEqual(getattr(wrapper, name), getattr(wrapped, name))
else:
self.assertIs(getattr(wrapper, name), getattr(wrapped, name))
# Check attributes were updated
for name in updated:
wrapper_attr = getattr(wrapper, name)
Expand All @@ -629,13 +636,14 @@ def wrapper(b:'This is the prior annotation'):

def test_default_update(self):
wrapper, f = self._default_update()
self.check_wrapper(wrapper, f)
self.check_wrapper(wrapper, f,
expected_annotations={'b': 'This is the prior annotation'})
self.assertIs(wrapper.__wrapped__, f)
self.assertEqual(wrapper.__name__, 'f')
self.assertEqual(wrapper.__qualname__, f.__qualname__)
self.assertEqual(wrapper.attr, 'This is also a test')
self.assertEqual(wrapper.__annotations__['a'], 'This is a new annotation')
self.assertNotIn('b', wrapper.__annotations__)
self.assertEqual(wrapper.__annotations__['b'], 'This is the prior annotation')
self.assertNotIn('a', wrapper.__annotations__)

@unittest.skipIf(sys.flags.optimize >= 2,
"Docstrings are omitted with -O2 and above")
Expand Down Expand Up @@ -1638,7 +1646,10 @@ def f(zomg: 'zomg_annotation'):
return 42
g = self.module.lru_cache()(f)
for attr in self.module.WRAPPER_ASSIGNMENTS:
self.assertEqual(getattr(g, attr), getattr(f, attr))
try:
self.assertEqual(getattr(g, attr), getattr(f, attr))
except AttributeError:
pass

@threading_helper.requires_working_threading()
def test_lru_cache_threaded(self):
Expand Down
5 changes: 3 additions & 2 deletions Lib/test/test_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -3038,8 +3038,9 @@ def bar(self, a, b):
self.assertEqual(self.signature(Foo.bar, follow_wrapped=False),
((('args', ..., ..., "var_positional"),
('kwargs', ..., ..., "var_keyword")),
...)) # functools.wraps will copy __annotations__
# from "func" to "wrapper", hence no
int)) # functools.wraps will copy __annotations__
# from "func" to "wrapper" only if wrapper does
# not have some already, hence the
# return_annotation

self.assertEqual(self.signature(bar),
Expand Down
27 changes: 27 additions & 0 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -5009,6 +5009,33 @@ def test_get_type_hints_wrapped_decoratored_func(self):
self.assertEqual(gth(ForRefExample.func), expects)
self.assertEqual(gth(ForRefExample.nested), expects)

def test_get_type_hints_wrapped_decoratored_func_only_with_return_type(self):
expects = {'arg1': str, 'return': bool}

@ann_module.dec_with_return_type
def func(arg1: str) -> int:
return 0

self.assertEqual(gth(func), expects)

def test_get_type_hints_wrapped_decoratored_func_only_with_arg_types(self):
expects = {'custom_arg': int, 'return': int}

@ann_module.dec_with_arg_types
def func(arg1: str) -> int:
return 0

self.assertEqual(gth(func), expects)

def test_get_type_hints_wrapped_decoratored_func_with_args_and_return_type(self):
expects = {'custom_arg': int, 'return': bool}

@ann_module.dec_with_args_and_return_types
def func(arg1: str) -> int:
return 0

self.assertEqual(gth(func), expects)

def test_get_type_hints_annotated(self):
def foobar(x: List['X']): ...
X = Annotated[int, (1, 10)]
Expand Down
1 change: 1 addition & 0 deletions Misc/ACKS
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,7 @@ Brett Cannon
Joshua Cannon
Tristan Carel
Mike Carlton
David Caro
Pierre Carrier
Terry Carroll
Edward Catmur
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
``update_wrapper``: Don't override the ``__annotations__`` of the wrapper
function if it has any as it might have a different signature than the
wrapped one, and using the wrapped might mask the actual types.