FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

bpo-40464: fix return annotation being used as the arg annotation in singledispatch by FFY00 · Pull Request #19871 · python/cpython · GitHub

Repository navigation

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .py  (2) .rst  (1) All 2 file types selected
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
11 changes: 8 additions & 3 deletions Lib/functools.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -862,7 +862,7 @@ def _is_valid_dispatch_type(cls):
return (_is_union_type(cls) and
all(isinstance(arg, type) for arg in get_args(cls)))

def register(cls, func=None):
def register(cls, func=None, _arg_index=0):
"""generic_func.register(cls, func) -> func

Registers a new implementation for the given *cls* on a *generic_func*.
Expand All @@ -878,8 +878,13 @@ def register(cls, func=None):
f"Invalid first argument to `register()`. "
f"{cls!r} is not a class or union type."
)
import inspect
try:
args = list(inspect.signature(cls).parameters.keys())
except TypeError:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

signature() can also raise a ValueError if no signature can be provided.

args = []
ann = getattr(cls, '__annotations__', {})
if not ann:
if len(args) <= _arg_index or args[_arg_index] not in ann:
raise TypeError(
f"Invalid first argument to `register()`: {cls!r}. "
f"Use either `@register(some_class)` or plain `@register` "
Expand Down Expand Up @@ -954,7 +959,7 @@ def register(self, cls, method=None):

Registers a new implementation for the given *cls* on a *generic_method*.
"""
return self.dispatcher.register(cls, func=method)
return self.dispatcher.register(cls, func=method, _arg_index=1)

def __get__(self, obj, cls=None):
if self._method_cache is not None:
Expand Down
33 changes: 33 additions & 0 deletions Lib/test/test_functools.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -2865,6 +2865,39 @@ def _(arg: typing.Union[int, typing.Iterable[str]]):
'typing.Union[int, typing.Iterable[str]] not all arguments are classes.'
))

with self.assertRaises(TypeError) as exc:
@i.register
def _(arg) -> str:
# At runtime, dispatching on generics is impossible.
# When registering implementations with singledispatch, avoid
# types from `typing`. Instead, annotate with regular types
# or ABCs.
return "I annotated with a generic collection"
self.assertTrue(str(exc.exception).startswith(
"Invalid first argument to `register()`:"
))
self.assertTrue(str(exc.exception).endswith(
'Use either `@register(some_class)` or plain `@register` on an annotated function.'
))

@functools.singledispatch
def i(arg1, arg2):
return "base"
with self.assertRaises(TypeError) as exc:
@i.register
def _(arg1, arg2: int) -> str:
# At runtime, dispatching on generics is impossible.
# When registering implementations with singledispatch, avoid
# types from `typing`. Instead, annotate with regular types
# or ABCs.
return "I annotated with a generic collection"
self.assertTrue(str(exc.exception).startswith(
"Invalid first argument to `register()`:"
))
self.assertTrue(str(exc.exception).endswith(
'Use either `@register(some_class)` or plain `@register` on an annotated function.'
))

def test_invalid_positional_argument(self):
@functools.singledispatch
def f(*args):
Expand Down
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix return annotation being used as the arg annotation in functools.singledispatch

Back | FazBrowse Home | New Git URL