8000 gh-82129: Improve annotations for make_dataclass() by JelleZijlstra · Pull Request #133406 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

gh-82129: Improve annotations for make_dataclass() #133406

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

Merged
merged 14 commits into from
May 5, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

< 8000 form class="js-file-filter-form" data-turbo="false" action="/" accept-charset="UTF-8" method="post">
Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
better
  • Loading branch information
JelleZijlstra committed May 4, 2025
commit 3d7eb6edb8438414dd6e683377ec57ad9edb7fe6
2 changes: 1 addition & 1 deletion Lib/annotationlib.py
8000
Original file line number Diff line number Diff line change
Expand Up @@ -788,7 +788,7 @@ def get_annotations(
# For FORWARDREF, we use __annotations__ if it exists
try:
ann = _get_dunder_annotations(obj)
except NameError:
except Exception:
Copy link
Member Author

Choose a reason for hiding this comment

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

I made a separate PR (with tests) for this change in #133407.

pass
else:
if ann is not None:
Expand Down
17 changes: 12 additions & 5 deletions Lib/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -1614,6 +1614,8 @@ class C(Base):
seen.add(name)
annotations[name] = tp

value_blocked = True

def annotate_method(format):
def get_any():
match format:
Expand All @@ -1626,6 +1628,8 @@ def get_any():
else:
return typing.Any
case annotationlib.Format.VALUE:
if value_blocked:
raise NotImplementedError
from typing import Any
return Any
case _:
Expand All @@ -1641,13 +1645,14 @@ def get_any():

# Update 'ns' with the user-supplied namespace plus our calculated values.
def exec_body_callback(ns):
ns['__annotate__'] = annotate_method
ns.update(namespace)
ns.update(defaults)

# We use `types.new_class()` instead of simply `type()` to allow dynamic creation
# of generic dataclasses.
cls = types.new_class(cls_name, bases, {}, exec_body_callback)
# For now, set annotations including the _ANY_MARKER.
cls.__annotate__ = annotate_method

# For pickling to work, the __module__ variable needs to be set to the frame
# where the dataclass is created.
Expand All @@ -1663,10 +1668,12 @@ def exec_body_callback(ns):
cls.__module__ = module

# Apply the normal provided decorator.
return decorator(cls, init=init, repr=repr, eq=eq, order=order,
unsafe_hash=unsafe_hash, frozen=frozen,
match_args=match_args, kw_only=kw_only, slots=slots,
weakref_slot=weakref_slot)
cls = decorator(cls, init=init, repr=repr, eq=eq, order=order,
unsafe_hash=unsafe_hash, frozen=frozen,
match_args=match_args, kw_only=kw_only, slots=slots,
weakref_slot=weakref_slot)
value_blocked = False
return cls


def replace(obj, /, **changes):
Expand Down
22 changes: 22 additions & 0 deletions Lib/test/test_dataclasses/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4277,6 +4277,28 @@ def test_no_types_get_annotations(self):
{'x': 'typing.Any', 'y': 'int', 'z': 'typing.Any'},
)

def test_no_types_no_typing_import(self):
with import_helper.CleanImport('typing'):
self.assertNotIn('typing', sys.modules)
C = make_dataclass('C', ['x', ('y', int)])

self.assertNotIn('typing', sys.modules)
self.assertEqual(
C.__annotate__(annotationlib.Format.FORWARDREF),
{
'x': annotationlib.ForwardRef('Any', module='typing'),
'y': int,
},
)
self.assertNotIn('typing', sys.modules)

for field in fields(C):
if field.name == "x":
self.assertEqual(field.type, annotationlib.ForwardRef('Any', module='typing'))
else:
self.assertEqual(field.name, "y")
self.assertIs(field.type, int)

def test_module_attr(self):
self.assertEqual(ByMakeDataClass.__module__, __name__)
self.assertEqual(ByMakeDataClass(1).__module__, __name__)
Expand Down
0