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
Next Next commit
gh-82128: Provide __annotate__ method for dataclasses from `make_da…
…taclass`
  • Loading branch information
sobolevn committed Jul 25, 2024
commit c2d85b7b03e472126e0561466c38adf231d0b99b
14 changes: 12 additions & 2 deletions Lib/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -1527,10 +1527,11 @@ class C(Base):
seen = set()
annotations = {}
defaults = {}
any_marker = object()
for item in fields:
if isinstance(item, str):
name = item
tp = 'typing.Any'
tp = any_marker
elif len(item) == 2:
name, tp, = item
elif len(item) == 3:
Expand All @@ -1549,11 +1550,20 @@ class C(Base):
seen.add(name)
annotations[name] = tp

def annotate_method(format):
if format != 1:
raise NotImplementedError
from typing import Any
return {
ann: Any if t is any_marker else t
for ann, t in annotations.items()
}

# 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)
ns['__annotations__'] = annotations

# We use `types.new_class()` instead of simply `type()` to allow dynamic creation
# of generic dataclasses.
Expand Down
Loading
0