Skip to content

Fix pickling of globally available, dynamically generated norm classes. #22815

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

Merged
merged 1 commit into from
Apr 10, 2022
Merged
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
23 changes: 20 additions & 3 deletions lib/matplotlib/colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
from collections.abc import Sized, Sequence
import copy
import functools
import importlib
import inspect
import io
import itertools
Expand Down Expand Up @@ -1528,9 +1529,22 @@ def _make_norm_from_scale(scale_cls, base_norm_cls, bound_init_signature):

class Norm(base_norm_cls):
def __reduce__(self):
cls = type(self)
# If the class is toplevel-accessible, it is possible to directly
# pickle it "by name". This is required to support norm classes
# defined at a module's toplevel, as the inner base_norm_cls is
# otherwise unpicklable (as it gets shadowed by the generated norm
# class). If either import or attribute access fails, fall back to
# the general path.
try:
if cls is getattr(importlib.import_module(cls.__module__),
cls.__qualname__):
return (_create_empty_object_of_class, (cls,), vars(self))
except (ImportError, AttributeError):
pass
return (_picklable_norm_constructor,
(scale_cls, base_norm_cls, bound_init_signature),
self.__dict__)
vars(self))

def __init__(self, *args, **kwargs):
ba = bound_init_signature.bind(*args, **kwargs)
Expand Down Expand Up @@ -1603,11 +1617,14 @@ def autoscale_None(self, A):
return Norm


def _picklable_norm_constructor(*args):
cls = _make_norm_from_scale(*args)
def _create_empty_object_of_class(cls):
return cls.__new__(cls)


def _picklable_norm_constructor(*args):
return _create_empty_object_of_class(_make_norm_from_scale(*args))


@make_norm_from_scale(
scale.FuncScale,
init=lambda functions, vmin=None, vmax=None, clip=False: None)
Expand Down
5 changes: 5 additions & 0 deletions lib/matplotlib/tests/test_pickle.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,11 @@ def test_mpl_toolkits():
assert type(pickle.loads(pickle.dumps(ax))) == parasite_axes.HostAxes


def test_standard_norm():
assert type(pickle.loads(pickle.dumps(mpl.colors.LogNorm()))) \
== mpl.colors.LogNorm


def test_dynamic_norm():
logit_norm_instance = mpl.colors.make_norm_from_scale(
mpl.scale.LogitScale, mpl.colors.Normalize)()
Expand Down