Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

gh-130827: Support typing.Self annotations in singledispatchmethod() #130829

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

Open
wants to merge 8 commits into
base: main
Choose a base branch
Loading
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
gh-130827: Support typing.Self in singledispatchmethod()
  • Loading branch information
ZeroIntensity committed Mar 4, 2025
commit d466dc40472da6f4e14e66493375a8c0674b10ab
36 changes: 24 additions & 12 deletions 36 Lib/functools.py
Original file line number Diff line number Diff line change
Expand Up @@ -885,15 +885,7 @@ def _find_impl(cls, registry):
match = t
return registry.get(match)

def singledispatch(func):
"""Single-dispatch generic function decorator.

Transforms a function into a generic function, which can have different
behaviours depending upon the type of its first argument. The decorated
function acts as the default implementation, and additional
implementations can be registered using the register() attribute of the
generic function.
"""
def _singledispatchimpl(func, is_method):
ZeroIntensity marked this conversation as resolved.
Show resolved Hide resolved
# There are many programs that use functools without singledispatch, so we
# trade-off making singledispatch marginally slower for the benefit of
# making start-up of such applications slightly faster.
Expand Down Expand Up @@ -963,9 +955,19 @@ def register(cls, func=None):
func = cls

# only import typing if annotation parsing is necessary
from typing import get_type_hints
from typing import get_type_hints, Self
from annotationlib import Format, ForwardRef
argname, cls = next(iter(get_type_hints(func, format=Format.FORWARDREF).items()))
hints_iter = iter(get_type_hints(func, format=Format.FORWARDREF).items())
argname, cls = next(hints_iter)
if cls is Self:
if not is_method:
raise TypeError(
f"Invalid annotation for {argname!r}. ",
"typing.Self can only be used with singledispatchmethod()"
)
else:
argname, cls = next(hints_iter)
ambv marked this conversation as resolved.
Show resolved Hide resolved

if not _is_valid_dispatch_type(cls):
if _is_union_type(cls):
raise TypeError(
Expand Down Expand Up @@ -1010,6 +1012,16 @@ def wrapper(*args, **kw):
update_wrapper(wrapper, func)
return wrapper

def singledispatch(func):
"""Single-dispatch generic function decorator.

Transforms a function into a generic function, which can have different
behaviours depending upon the type of its first argument. The decorated
function acts as the default implementation, and additional
implementations can be registered using the register() attribute of the
generic function.
"""
return _singledispatchimpl(func, is_method=False)

# Descriptor version
class singledispatchmethod:
Expand All @@ -1023,7 +1035,7 @@ def __init__(self, func):
if not callable(func) and not hasattr(func, "__get__"):
raise TypeError(f"{func!r} is not callable or a descriptor")

self.dispatcher = singledispatch(func)
self.dispatcher = _singledispatchimpl(func, is_method=True)
self.func = func

def register(self, cls, method=None):
Expand Down
24 changes: 24 additions & 0 deletions 24 Lib/test/test_functools.py
Original file line number Diff line number Diff line change
Expand Up @@ -3362,6 +3362,30 @@ def _(item, arg: bytes) -> str:
self.assertEqual(str(Signature.from_callable(A.static_func)),
'(item, arg: int) -> str')

def test_typing_self(self):
# gh-130827: typing.Self with singledispatchmethod() didn't work
class Foo:
@functools.singledispatchmethod
def bar(self: typing.Self, arg: int | str) -> int | str: ...

@bar.register
def _(self: typing.Self, arg: int) -> int:
return arg


foo = Foo()
self.assertEqual(foo.bar(42), 42)

@functools.singledispatch
def test(self: typing.Self, arg: int | str) -> int | str:
pass
# But, it shouldn't work on singledispatch()
with self.assertRaises(TypeError):
@test.register
def silly(self: typing.Self, arg: int | str) -> int | str:
Copy link
Member

Choose a reason for hiding this comment

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

Will 'typing.Self' annotation work the same way?

Copy link
Member Author

Choose a reason for hiding this comment

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

Good question! It should, yeah. get_type_hints handles forward references.

Copy link
Member

Choose a reason for hiding this comment

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

Should we add a test case for that, maybe?

Copy link
Member Author

Choose a reason for hiding this comment

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

Possibly, but as long as get_type_hints is working it's probably fine.

pass

ZeroIntensity marked this conversation as resolved.
Show resolved Hide resolved


class CachedCostItem:
_cost = 1
Expand Down
Morty Proxy This is a proxified and sanitized view of the page, visit original site.