Skip to content

gh-82129: Fix NameError on get_type_hints in dataclasses#122232

Closed
sobolevn wants to merge 3 commits intopython:mainfrom
sobolevn:issue-82129
Closed

gh-82129: Fix NameError on get_type_hints in dataclasses#122232
sobolevn wants to merge 3 commits intopython:mainfrom
sobolevn:issue-82129

Conversation

@sobolevn
Copy link
Member

@sobolevn sobolevn commented Jul 24, 2024

Ok, here's my attempt at solving this.

When you call typing.get_type_hints you still have to import typing.
There's a good chance that it will already be imported by something else in your sys.modules.

We already have this hack in other places:

cpython/Lib/dataclasses.py

Lines 809 to 815 in e968121

typing = sys.modules.get('typing')
if typing:
if (_is_classvar(a_type, typing)
or (isinstance(f.type, str)
and _is_type(f.type, cls, typing, typing.ClassVar,
_is_classvar))):
f._field_type = _FIELD_CLASSVAR

So, this solution can be used to hide the problem for older versions of python (down to 3.12). While we can actually fully solve with annotationlib in 3.14+

I think that this hack + user-space one:

S = make_dataclass('S', ['x'])
get_type_hints(S, {'typing': typing})

is good enough for now.

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants