Skip to content

Commit

Permalink
Allow attributes to be called property and itemgetter (#430)
Browse files Browse the repository at this point in the history
* Allow attributes to be called property and itemgetter

* Add newsfragment
  • Loading branch information
hynek committed Aug 21, 2018
1 parent 6a07b03 commit 068cd0b
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
1 change: 1 addition & 0 deletions changelog.d/430.change.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Attributes can be named ``property`` and ``itemgetter`` now.
7 changes: 5 additions & 2 deletions src/attr/_make.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@
_obj_setattr = object.__setattr__
_init_converter_pat = "__attr_converter_{}"
_init_factory_pat = "__attr_factory_{}"
_tuple_property_pat = " {attr_name} = property(itemgetter({index}))"
_tuple_property_pat = (
" {attr_name} = _attrs_property(_attrs_itemgetter({index}))"
)
_classvar_prefixes = ("typing.ClassVar", "t.ClassVar", "ClassVar")
# we don't use a double-underscore prefix because that triggers
# name mangling when trying to create a slot for the field
Expand Down Expand Up @@ -243,8 +245,9 @@ class MyClassAttributes(tuple):
)
else:
attr_class_template.append(" pass")
globs = {"itemgetter": itemgetter}
globs = {"_attrs_itemgetter": itemgetter, "_attrs_property": property}
eval(compile("\n".join(attr_class_template), "", "exec"), globs)

return globs[attr_class_name]


Expand Down
15 changes: 15 additions & 0 deletions tests/test_dark_magic.py
Original file line number Diff line number Diff line change
Expand Up @@ -482,3 +482,18 @@ class Sub(Base):

with pytest.raises(FrozenInstanceError):
i.b = "3"

def test_tuple_class_aliasing(self):
"""
itemgetter and property are legal attribute names.
"""

@attr.s
class C(object):
property = attr.ib()
itemgetter = attr.ib()
x = attr.ib()

assert "property" == attr.fields(C).property.name
assert "itemgetter" == attr.fields(C).itemgetter.name
assert "x" == attr.fields(C).x.name

0 comments on commit 068cd0b

Please sign in to comment.