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

Convert transformed attrs to AttrsClass #824

Merged
merged 9 commits into from Sep 22, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/824.changes.rst
@@ -0,0 +1 @@
Attributes transformed via ``field_transformer`` are wrapped with ``AttrsClass`` again.
14 changes: 8 additions & 6 deletions src/attr/_make.py
Expand Up @@ -581,15 +581,11 @@ def _transform_attrs(
cls, {a.name for a in own_attrs}
)

attr_names = [a.name for a in base_attrs + own_attrs]

AttrsClass = _make_attr_tuple_class(cls.__name__, attr_names)

if kw_only:
own_attrs = [a.evolve(kw_only=True) for a in own_attrs]
base_attrs = [a.evolve(kw_only=True) for a in base_attrs]

attrs = AttrsClass(base_attrs + own_attrs)
attrs = base_attrs + own_attrs

# Mandatory vs non-mandatory attr order only matters when they are part of
# the __init__ signature and when they aren't kw_only (which are moved to
Expand All @@ -608,7 +604,13 @@ def _transform_attrs(

if field_transformer is not None:
attrs = field_transformer(cls, attrs)
return _Attributes((attrs, base_attrs, base_attr_map))

# Create AttrsClass *after* applying the field_transformer since it may
# add or remove attributes!
attr_names = [a.name for a in attrs]
AttrsClass = _make_attr_tuple_class(cls.__name__, attr_names)

return _Attributes((AttrsClass(attrs), base_attrs, base_attr_map))


if PYPY:
Expand Down
16 changes: 16 additions & 0 deletions tests/test_hooks.py
Expand Up @@ -117,6 +117,22 @@ class Sub(Base):

assert attr.asdict(Sub(2)) == {"y": 2}

def test_attrs_attrclass(self):
"""
The list of attrs returned by a field_transformer is converted to
"AttrsClass" again.

Regression test for #821.
"""

@attr.s(auto_attribs=True, field_transformer=lambda c, a: list(a))
class C:
x: int

fields_type = type(attr.fields(C))
assert fields_type.__name__ == "CAttributes"
assert issubclass(fields_type, tuple)


class TestAsDictHook:
def test_asdict(self):
Expand Down