Skip to content

Commit

Permalink
pythongh-82128: Provide __annotate__ method for dataclasses from `m…
Browse files Browse the repository at this point in the history
…ake_dataclass`
  • Loading branch information
sobolevn committed Jul 25, 2024
1 parent a3327db commit c2d85b7
Showing 1 changed file with 12 additions and 2 deletions.
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

0 comments on commit c2d85b7

Please sign in to comment.