Skip to content

update NDFrame __setattr__ to match behavior of __getattr__ #9004

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

Closed
wants to merge 3 commits into from
Closed
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
17 changes: 17 additions & 0 deletions doc/source/whatsnew/v0.15.2.txt
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,23 @@ API changes

- Allow equality comparisons of Series with a categorical dtype and object dtype; previously these would raise ``TypeError`` (:issue:`8938`)

- Bug in ``NDFrame``: conflicting attribute/column names now behave consistently between getting and setting. Previously, when both a column and attribute named ``y`` existed, ``data.y`` would return the attribute, while ``data.y = z`` would update the column (:issue:`8994`)

.. ipython:: python

data = pd.DataFrame({'x':[1, 2, 3]})
data.y = 2
data['y'] = [2, 4, 6]
data.y = 5 # this assignment was inconsistent

print(data.y)
# prior output : 2
# 0.15.2 output: 5

print(data['y'].values)
# prior output : [5, 5, 5]
# 0.15.2 output: [2, 4, 6]

.. _whatsnew_0152.enhancements:

Enhancements
Expand Down
23 changes: 18 additions & 5 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1929,11 +1929,12 @@ def __finalize__(self, other, method=None, **kwargs):
return self

def __getattr__(self, name):
"""After regular attribute access, try looking up the name of a the
info.

"""After regular attribute access, try looking up the name
This allows simpler access to columns for interactive use.
"""
# Note: obj.x will always call obj.__getattribute__('x') prior to
# calling obj.__getattr__('x').

if name in self._internal_names_set:
return object.__getattribute__(self, name)
elif name in self._metadata:
Expand All @@ -1945,12 +1946,24 @@ def __getattr__(self, name):
(type(self).__name__, name))

def __setattr__(self, name, value):
"""After regular attribute access, try looking up the name of the info
"""After regular attribute access, try setting the name
This allows simpler access to columns for interactive use."""
# first try regular attribute access via __getattribute__, so that
# e.g. ``obj.x`` and ``obj.x = 4`` will always reference/modify
# the same attribute.

try:
object.__getattribute__(self, name)
return object.__setattr__(self, name, value)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you don't need to return here (not that it really matters, but you did remove the unnecessary return below!)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It was either this, or this followed by return None. I decided to go for brevity 😄

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, I see why it's needed now :)

except AttributeError:
pass

# if this fails, go on to more involved attribute setting
# (note that this matches __getattr__, above).
if name in self._internal_names_set:
object.__setattr__(self, name, value)
elif name in self._metadata:
return object.__setattr__(self, name, value)
object.__setattr__(self, name, value)
else:
try:
existing = getattr(self, name)
Expand Down
13 changes: 13 additions & 0 deletions pandas/tests/test_generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
assert_frame_equal,
assert_panel_equal,
assert_almost_equal,
assert_equal,
ensure_clean)
import pandas.util.testing as tm

Expand Down Expand Up @@ -1316,6 +1317,18 @@ def test_tz_convert_and_localize(self):
df = DataFrame(index=l0)
df = getattr(df, fn)('US/Pacific', level=1)

def test_set_attribute(self):
# Test for consistent setattr behavior when an attribute and a column
# have the same name (Issue #8994)
df = DataFrame({'x':[1, 2, 3]})

df.y = 2
df['y'] = [2, 4, 6]
df.y = 5

assert_equal(df.y, 5)
assert_series_equal(df['y'], Series([2, 4, 6]))


class TestPanel(tm.TestCase, Generic):
_typ = Panel
Expand Down