Skip to content
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

make_class(): Add "__annotations_" to generated class #1285

Merged
merged 4 commits into from
Jul 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/1285.change.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`attrs.make_class()` now populates the `__annotations__` dict of the generated class, so that `attrs.resolve_types()` can resolve them.
7 changes: 6 additions & 1 deletion src/attr/_make.py
Original file line number Diff line number Diff line change
Expand Up @@ -3056,7 +3056,12 @@ def make_class(
True,
)

return _attrs(these=cls_dict, **attributes_arguments)(type_)
cls = _attrs(these=cls_dict, **attributes_arguments)(type_)
# Only add type annotations now or "_attrs()" will complain:
cls.__annotations__ = {
k: v.type for k, v in cls_dict.items() if v.type is not None
}
return cls


# These are required by within this module so we define them here and merely
Expand Down
28 changes: 28 additions & 0 deletions tests/test_make.py
Original file line number Diff line number Diff line change
Expand Up @@ -1164,6 +1164,34 @@ def test_generic_dynamic_class(self):

attr.make_class("test", {"id": attr.ib(type=str)}, (MyParent[int],))

def test_annotations(self):
"""
make_class fills the __annotations__ dict for attributes with a known
type.
"""
a = attr.ib(type=bool)
b = attr.ib(
type=None
) # Won't be added to ann. b/c of unfavorable default
c = attr.ib()

C = attr.make_class("C", {"a": a, "b": b, "c": c})
C = attr.resolve_types(C)

assert {"a": bool} == C.__annotations__

def test_annotations_resolve(self):
"""
resolve_types() resolves the annotations added by make_class().
"""
a = attr.ib(type="bool")

C = attr.make_class("C", {"a": a})
C = attr.resolve_types(C)

assert attr.fields(C).a.type is bool
assert {"a": "bool"} == C.__annotations__


class TestFields:
"""
Expand Down