8000 MNT: don't set method objects back onto the objects · matplotlib/matplotlib@73855bf · GitHub
[go: up one dir, main page]

Skip to content

Commit 73855bf

Browse files
committed
MNT: don't set method objects back onto the objects
If we are monkey-patching methods then we need to be sure that when we restore the original attribute we need to make sure we don't stick the method instance in place (which creates a circular reference).
1 parent 4356b67 commit 73855bf

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

lib/matplotlib/cbook/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import types
2525
import warnings
2626
import weakref
27+
import inspect
2728

2829
import numpy as np
2930

@@ -2039,7 +2040,7 @@ def _setattr_cm(obj, **kwargs):
20392040
yield
20402041
finally:
20412042
for attr, orig in origs:
2042-
if orig is sentinel:
2043+
if orig is sentinel or inspect.ismethod(orig):
20432044
delattr(obj, attr)
20442045
else:
20452046
setattr(obj, attr, orig)

lib/matplotlib/tests/test_cbook.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -651,3 +651,26 @@ def test_check_shape(target, test_shape):
651651
with pytest.raises(ValueError,
652652
match=error_pattern):
653653
cbook._check_shape(target, aardvark=data)
654+
655+
656+
def test_setattr_cm():
657+
class A:
658+
def __init__(self):
659+
self.aardvark = 'aardvark'
660+
661+
def meth(self):
662+
...
663+
664+
a = A()
665+
666+
assert id(a.meth) != id(a.meth)
667+
assert id(a.aardvark) == id(a.aardvark)
668+
669+
with cbook._setattr_cm(a, aardvark='moose', meth=lambda: None):
670+
assert id(a.meth) == id(a.meth)
671+
assert id(a.aardvark) == id(a.aardvark)
672+
assert a.aardvark == 'moose'
673+
674+
assert id(a.meth) != id(a.meth)
675+
assert id(a.aardvark) == id(a.aardvark)
676+
assert a.aardvark == 'aardvark'

0 commit comments

Comments
 (0)
0