Skip to content

Commit a96efef

Browse files
committed
pythongh-82129: Fix NameError on get_type_hints in dataclasses
1 parent af4329e commit a96efef

File tree

2 files changed

+23
-6
lines changed

2 files changed

+23
-6
lines changed

Lib/dataclasses.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1530,7 +1530,11 @@ class C(Base):
15301530
for item in fields:
15311531
if isinstance(item, str):
15321532
name = item
1533-
tp = 'typing.Any'
1533+
typing = sys.modules.get('typing')
1534+
if typing:
1535+
tp = typing.Any
1536+
else:
1537+
tp = 'typing.Any'
15341538
elif len(item) == 2:
15351539
name, tp, = item
15361540
elif len(item) == 3:

Lib/test/test_dataclasses/__init__.py

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import weakref
1414
import traceback
1515
import unittest
16+
import sys
1617
from unittest.mock import Mock
1718
from typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict
1819
from typing import get_type_hints
@@ -23,6 +24,7 @@
2324
import dataclasses # Needed for the string "dataclasses.InitVar[int]" to work as an annotation.
2425

2526
from test import support
27+
from test.support import import_helper
2628

2729
# Just any custom exception we can catch.
2830
class CustomError(Exception): pass
@@ -4108,16 +4110,27 @@ def test_no_types(self):
41084110
C = make_dataclass('Point', ['x', 'y', 'z'])
41094111
c = C(1, 2, 3)
41104112
self.assertEqual(vars(c), {'x': 1, 'y': 2, 'z': 3})
4111-
self.assertEqual(C.__annotations__, {'x': 'typing.Any',
4112-
'y': 'typing.Any',
4113-
'z': 'typing.Any'})
4113+
self.assertEqual(C.__annotations__, {'x': typing.Any,
4114+
'y': typing.Any,
4115+
'z': typing.Any})
41144116

41154117
C = make_dataclass('Point', ['x', ('y', int), 'z'])
41164118
c = C(1, 2, 3)
41174119
self.assertEqual(vars(c), {'x': 1, 'y': 2, 'z': 3})
4118-
self.assertEqual(C.__annotations__, {'x': 'typing.Any',
4120+
self.assertEqual(C.__annotations__, {'x': typing.Any,
41194121
'y': int,
4120-
'z': 'typing.Any'})
4122+
'z': typing.Any})
4123+
4124+
def test_no_types_no_NameError(self):
4125+
C = make_dataclass('Point', ['x'])
4126+
self.assertEqual(C.__annotations__, {'x': typing.Any})
4127+
self.assertEqual(get_type_hints(C), {'x': typing.Any})
4128+
4129+
def test_no_types_no_typing_fallback(self):
4130+
with import_helper.isolated_modules():
4131+
del sys.modules['typing']
4132+
C = make_dataclass('Point', ['x'])
4133+
self.assertEqual(C.__annotations__, {'x': 'typing.Any'})
41214134

41224135
def test_module_attr(self):
41234136
self.assertEqual(ByMakeDataClass.__module__, __name__)

0 commit comments

Comments
 (0)