Skip to content

MNT: handle generic descriptors in _setattr_cm #17561

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 1 commit into from
Closed
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
19 changes: 14 additions & 5 deletions lib/matplotlib/cbook/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import contextlib
import functools
import gzip
import inspect
import itertools
import math
import operator
Expand Down Expand Up @@ -1961,6 +1962,10 @@ def _array_patch_perimeters(x, rstride, cstride):
def _setattr_cm(obj, **kwargs):
"""
Temporarily set some attributes; restore original state at context exit.

.. warning ::

This is not threadsafe.
"""
sentinel = object()
origs = {}
Expand All @@ -1978,14 +1983,18 @@ def _setattr_cm(obj, **kwargs):
# we want to set the original value back.
if isinstance(cls_orig, property):
origs[attr] = orig

# detect when we have Python Descriptors that supports
# setting so we will need to restore it
#
# https://docs.python.org/3/howto/descriptor.html
if hasattr(inspect.getattr_static(type(obj), attr), '__set__'):
origs[attr] = orig

# otherwise this is _something_ we are going to shadow at
# the instance dict level from higher up in the MRO. We
# are going to assume we can delattr(obj, attr) to clean
# up after ourselves. It is possible that this code will
# fail if used with a non-property custom descriptor which
# implements __set__ (and __delete__ does not act like a
# stack). However, this is an internal tool and we do not
# currently have any custom descriptors.
# up after ourselves.
else:
origs[attr] = sentinel

Expand Down