Skip to content

Commit 43ca51f

Browse files
authored
BUG: Fix implementation of temp_setattr (#45954)
1 parent 77915f4 commit 43ca51f

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

pandas/core/common.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -545,8 +545,10 @@ def temp_setattr(obj, attr: str, value) -> Iterator[None]:
545545
"""
546546
old_value = getattr(obj, attr)
547547
setattr(obj, attr, value)
548-
yield obj
549-
setattr(obj, attr, old_value)
548+
try:
549+
yield obj
550+
finally:
551+
setattr(obj, attr, old_value)
550552

551553

552554
def require_length_match(data, index: Index):

pandas/tests/test_common.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,3 +213,19 @@ def test_frozenlist(self):
213213
result = df[frozen]
214214
expected = df[[]]
215215
tm.assert_frame_equal(result, expected)
216+
217+
218+
@pytest.mark.parametrize("with_exception", [True, False])
219+
def test_temp_setattr(with_exception):
220+
# GH#45954
221+
ser = Series(dtype=object)
222+
ser.name = "first"
223+
# Raise a ValueError in either case to satisfy pytest.raises
224+
match = "Inside exception raised" if with_exception else "Outside exception raised"
225+
with pytest.raises(ValueError, match=match):
226+
with com.temp_setattr(ser, "name", "second"):
227+
assert ser.name == "second"
228+
if with_exception:
229+
raise ValueError("Inside exception raised")
230+
raise ValueError("Outside exception raised")
231+
assert ser.name == "first"

0 commit comments

Comments
 (0)