gh-89687: fix get_type_hints with dataclasses __init__ generation#137168
gh-89687: fix get_type_hints with dataclasses __init__ generation#137168Tishka17 wants to merge 2 commits intopython:mainfrom
Conversation
|
Most changes to Python require a NEWS entry. Add one using the blurb_it web app or the blurb command-line tool. If this change has little impact on Python users, wait for a maintainer to apply the |
|
As I see at this point:
|
|
|
||
| arg = self.__forward_arg__ | ||
| if arg.isidentifier() and not keyword.iskeyword(arg): | ||
| if self.__forward_module__ is not None: |
There was a problem hiding this comment.
I don't think this is correct, since we infer globals from __forward_module__ if no explicit globals are given. And if explicit globals are given, we shouldn't be using __forward_module__.
There was a problem hiding this comment.
I don't think current behavior is correct. Was there any discussion?
| # Return the text of the line in the body of __init__ that will | ||
| # initialize this field. | ||
|
|
||
| if f.init and isinstance(f.type, str): |
There was a problem hiding this comment.
Something like this is good, but I'd do it like this:
diff --git a/Lib/dataclasses.py b/Lib/dataclasses.py
index 53b3b54cfb3..e3d25fb0840 100644
--- a/Lib/dataclasses.py
+++ b/Lib/dataclasses.py
@@ -789,7 +789,10 @@ def _get_field(cls, a_name, a_type, default_kw_only):
# Only at this point do we know the name and the type. Set them.
f.name = a_name
- f.type = a_type
+ if isinstance(a_type, str):
+ f.type = annotationlib.ForwardRef(a_type, owner=cls)
+ else:
+ f.type = a_type
# Assume it's a normal field until proven otherwise. We're next
# going to decide if it's a ClassVar or InitVar, everything else
ForwardRef now lives in annotationlib, not typing. There's no need to catch SyntaxError as it doesn't parse its input in the constructor.
Fixes for #89687
Based on original #29158