You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
singledispatchmethod raises an error when relying on a forward declaration #86153
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
assignee=Noneclosed_at=Nonecreated_at=<Date2020-10-09.20:11:43.528>labels= ['type-bug', 'library', '3.9', '3.10']
title='singledispatchmethod raises an error when relying on a forward declaration'updated_at=<Date2022-01-11.09:46:19.220>user='https://github.com/glyph'
I spent some time debugging this looking for the root cause.
I think it looks like the recursion check in ForwardRef._evaluate() fails to trigger. At some point recursive_guard is a frozen set containing "'Integer'" (i.e. a string whose first and last character are single quotes, while self.__forward_arg__ is 'Integer' (i.e. a string that does not contain quotes).
I'm running out of time for the rest of the investigation, so feel free to confirm this and go down the rabbit hole from there...
mental32 commented on Nov 12, 2020
mental32mannequin
Mannequin
More actions
Interesting! thanks for the hint guido I'll try to investigate further.
This sounds like a regression (to me at least), in that case should a separate issue & patch PR be opened on the bpo or should this issue be used instead?
from __future__ importannotationsfromtypingimportget_type_hintsclassC:
deffunc(self, a: "C"):
passprint(get_type_hints(func))
In 3.8 this prints
{'a': ForwardRef('C')}
whilein3.9itraisesNameError:
Traceback (most recent call last):
File "C:\Users\gvanrossum\cpython\t.py", line 4, in <module>classC:
File "C:\Users\gvanrossum\cpython\t.py", line 8, in Cprint(get_type_hints(func))
File "C:\Python39\lib\typing.py", line 1386, in get_type_hints
value = _eval_type(value, globalns, localns)
File "C:\Python39\lib\typing.py", line 254, in _eval_typereturn t._evaluate(globalns, localns, recursive_guard)
File "C:\Python39\lib\typing.py", line 497, in _evaluateself.__forward_value__ = _eval_type(
File "C:\Python39\lib\typing.py", line 254, in _eval_typereturn t._evaluate(globalns, localns, recursive_guard)
File "C:\Python39\lib\typing.py", line 493, in _evaluateeval(self.__forward_code__, globalns, localns),
File "<string>", line 1, in <module>NameError: name 'C' is not defined
So the biggest difference I see is that ForwardRef._evaluate() has grown a recursive_guard argument in 3.9. This makes me think that in 3.8, only one level of evaluation was happening, and in 3.8, we keep evaluating until we don't see a string or ForwardRef.
The specific examples all happen at a point where the forward ref "C" cannot be resolved at all yet (since they're happening *in the class body*).
Possibly the best way out is to treat unresolved references differently, and just return the ForwardRef to the caller -- after all this is what the example does in 3.8.
ryansobol commented on Nov 12, 2020
ryansobolmannequin
Mannequin
More actions
Does anyone know why the treatment of unresolved references was changed in 3.9?
ryansobol commented on Nov 12, 2020
ryansobolmannequin
Mannequin
More actions
Also, I'm a bit puzzled about something from the previously mentioned Integer class and its use of __future__.annotations.
Why is it possible to declare an Integer return type for the add() method, but only possible to declare an "Integer" forward reference for the _() method?
Does anyone know why the treatment of unresolved references was changed in 3.9?
Probably to prepare for 3.10, where from _future__ import annotations is the default.
Also, I'm a bit puzzled about something from the previously mentioned Integer class and its use of __future__.annotations.
Why is it possible to declare an Integer return type for the add() method, but only possible to declare an "Integer" forward reference for the _() method?
I don't know -- you might want to look through the source code of singledispatch. Maybe the flow through the initial decorator is different than the flow through register().
Thanks for the bisection. It's not surprising that that's the culprit, and in other situations that's the right thing to do. I'm not sure how to address this without breaking other stuff -- maybe leave the ForwardRef if evaluating it doesn't work? But that's likely to have other subtle side effects -- we still want simple typos (or other reasons why a reference is legitimately broken) to go unchecked. Maybe singledispatch can catch the error and fall back on looking at bare __annotations__?
This can probably be closed as it's not an issue in Py 3.10+
I can still reproduce the issue, so I can't confirm this. What exactly changed in Python 3.10?
First, regarding the problem discussed in #86153 (comment) and further on: this remained unfixed in 3.9, 3.10, 3.11, 3.12 and 3.13. It was fixed by PEP 749, precisely by 7b7b90d (GH-119891):
t.py:
from __future__ importannotationsfromfunctoolsimportsingledispatchmethodclassInteger:
@singledispatchmethoddefadd(self, other: object) ->Integer:
raiseNotImplementedError(f"Unsupported type {type(other)}")
@add.registerdef_(self, other: int) ->"Integer":
...
print("ok!")
❯ uvx every-python run 7b7b90d~ python t.py |& tail -n 1
NameError: name 'Integer' is not defined
❯ uvx every-python run 7b7b90d python t.py |& tail -n 1
ok!
Therefore, this is no longer a bug to fix.
The original error reported by the OP still reproduces on 3.15:
As @isidentical noted, the reason why this didn't work in the first place is that @register evaluates the annotation immediately, and at the time of evaluation the class body is still executing to complete the class namespace; the final class object is not available in any way yet. There is no way to get to the class object, because it simply doesn't exist at this time.
One simple solution that comes to my mind is delaying registrations entirely by moving them to __set_name__ of singledispatchmethod, when the class object is ready. singledispatchmethod.register() would simply queue registrations and __set_name__ would flush it to the singledispatch registry in the context of the finalized class.
Doing this to all registrations could break .dispatch calls inside the class body, but that seems like poor programming to me.
If that is a concern though, we could only queue unresolvable registrations, but that gives us a complicated flow to reason about + implementation complexity.
Activity
gvanrossum commentedon Oct 30, 2020
I'm not an expert on singledispatch. It seems the get_type_hints() call is present in 3.8 as well.
Could you investigate and find a root cause? Then maybe we can fix it. (If you come up with a PR that would be very much appreciated.)
gvanrossum commentedon Nov 11, 2020
I spent some time debugging this looking for the root cause.
I think it looks like the recursion check in ForwardRef._evaluate() fails to trigger. At some point recursive_guard is a frozen set containing "'Integer'" (i.e. a string whose first and last character are single quotes, while self.__forward_arg__ is 'Integer' (i.e. a string that does not contain quotes).
I'm running out of time for the rest of the investigation, so feel free to confirm this and go down the rabbit hole from there...
mental32 commentedon Nov 12, 2020
Interesting! thanks for the hint guido I'll try to investigate further.
This sounds like a regression (to me at least), in that case should a separate issue & patch PR be opened on the bpo or should this issue be used instead?
gvanrossum commentedon Nov 12, 2020
Keep this issue.
gvanrossum commentedon Nov 12, 2020
FWIW here's a minimal demo:
In 3.8 this prints
{'a': ForwardRef('C')}
gvanrossum commentedon Nov 12, 2020
So the biggest difference I see is that ForwardRef._evaluate() has grown a recursive_guard argument in 3.9. This makes me think that in 3.8, only one level of evaluation was happening, and in 3.8, we keep evaluating until we don't see a string or ForwardRef.
The specific examples all happen at a point where the forward ref "C" cannot be resolved at all yet (since they're happening *in the class body*).
Possibly the best way out is to treat unresolved references differently, and just return the ForwardRef to the caller -- after all this is what the example does in 3.8.
ryansobol commentedon Nov 12, 2020
Does anyone know why the treatment of unresolved references was changed in 3.9?
ryansobol commentedon Nov 12, 2020
Also, I'm a bit puzzled about something from the previously mentioned Integer class and its use of __future__.annotations.
Why is it possible to declare an Integer return type for the add() method, but only possible to declare an "Integer" forward reference for the _() method?
gvanrossum commentedon Nov 12, 2020
Probably to prepare for 3.10, where
from _future__ import annotationsis the default.I don't know -- you might want to look through the source code of singledispatch. Maybe the flow through the initial decorator is different than the flow through register().
joernheissler commentedon Jan 3, 2022
Hello!
git-bisect points at
https://bugs.python.org/issue41341
#21553
It breaks both the examples from
https://bugs.python.org/issue41987#msg379896 and
https://bugs.python.org/issue41987#msg380803
gvanrossum commentedon Jan 11, 2022
Thanks for the bisection. It's not surprising that that's the culprit, and in other situations that's the right thing to do. I'm not sure how to address this without breaking other stuff -- maybe leave the ForwardRef if evaluating it doesn't work? But that's likely to have other subtle side effects -- we still want simple typos (or other reasons why a reference is legitimately broken) to go unchecked. Maybe singledispatch can catch the error and fall back on looking at bare __annotations__?
pythonGH-86153: get_type_hints now parses forward reference properly
pythonGH-86153: Created a test for get_type_hints based on GVR's exam…
ashb commentedon Jan 13, 2025
This can probably be closed as it's not an issue in Py 3.10+
bintime: Work around python/cpython#86153
Add bintime submodule (#73)
johnslavik commentedon Jan 6, 2026
I can still reproduce the issue, so I can't confirm this. What exactly changed in Python 3.10?
First, regarding the problem discussed in #86153 (comment) and further on: this remained unfixed in 3.9, 3.10, 3.11, 3.12 and 3.13. It was fixed by PEP 749, precisely by 7b7b90d (GH-119891):
t.py:Therefore, this is no longer a bug to fix.
The original error reported by the OP still reproduces on 3.15:
with a lovely error message:
(Without
from __future__ import annotationson top we also get nearly the same error).It's not a bug report, but a feature request, as previously noted by @isidentical in #86153 (comment) and by @gvanrossum in #86153 (comment). I'm relabeling this issue accordingly.
As @isidentical noted, the reason why this didn't work in the first place is that
@registerevaluates the annotation immediately, and at the time of evaluation the class body is still executing to complete the class namespace; the final class object is not available in any way yet. There is no way to get to the class object, because it simply doesn't exist at this time.One simple solution that comes to my mind is delaying registrations entirely by moving them to
__set_name__ofsingledispatchmethod, when the class object is ready.singledispatchmethod.register()would simply queue registrations and__set_name__would flush it to the singledispatch registry in the context of the finalized class.Doing this to all registrations could break
.dispatchcalls inside the class body, but that seems like poor programming to me.If that is a concern though, we could only queue unresolvable registrations, but that gives us a complicated flow to reason about + implementation complexity.
johnslavik commentedon Jan 20, 2026
Revisiting this, I think it's not worth it.
This is easy and works:
The cost of changing the assumptions that singledispatch was built on is IMO too high to support this one edge case.
kyleaoman commentedon May 20, 2026
@johnslavik the suggested workaround:
does work at runtime, but results in a
mypyerror:error: "Callable[..., Any]" has no attribute "register" [attr-defined]