Skip to content

Fix xkcd style garbage collection. #10856

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
Mar 21, 2018
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
37 changes: 25 additions & 12 deletions lib/matplotlib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1246,8 +1246,7 @@ def rc_file(fname):
rcParams.update(rc_params_from_file(fname))


@contextlib.contextmanager
def rc_context(rc=None, fname=None):
class rc_context:
"""
Return a context manager for managing rc settings.

Expand Down Expand Up @@ -1277,19 +1276,33 @@ def rc_context(rc=None, fname=None):
ax.plot(range(3), range(3))
fig.savefig('A.png', format='png')
plt.close(fig)

"""
# While it may seem natural to implement rc_context using
# contextlib.contextmanager, that would entail always calling the finally:
# clause of the contextmanager (which restores the original rcs) including
# during garbage collection; as a result, something like `plt.xkcd();
# gc.collect()` would result in the style being lost (as `xkcd()` is
# implemented on top of rc_context, and nothing is holding onto context
# manager except possibly circular references.

def __init__(self, rc=None, fname=None):
self._orig = rcParams.copy()
try:
if fname:
rc_file(fname)
if rc:
rcParams.update(rc)
except Exception:
# If anything goes wrong, revert to the original rcs.
dict.update(rcParams, self._orig)
raise

orig = rcParams.copy()
try:
if fname:
rc_file(fname)
if rc:
rcParams.update(rc)
yield
finally:
def __enter__(self):
return self

def __exit__(self, exc_type, exc_value, exc_tb):
# No need to revalidate the original values.
dict.update(rcParams, orig)
dict.update(rcParams, self._orig)


_use_error_msg = """
Expand Down
17 changes: 1 addition & 16 deletions lib/matplotlib/pyplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,7 +387,7 @@ def xkcd(scale=1, length=100, randomness=2):
"xkcd mode is not compatible with text.usetex = True")

from matplotlib import patheffects
xkcd_ctx = rc_context({
return rc_context({
'font.family': ['xkcd', 'Humor Sans', 'Comic Sans MS'],
'font.size': 14.0,
'path.sketch': (scale, length, randomness),
Expand All @@ -404,21 +404,6 @@ def xkcd(scale=1, length=100, randomness=2):
'ytick.major.size': 8,
'ytick.major.width': 3,
})
xkcd_ctx.__enter__()

# In order to make the call to `xkcd` that does not use a context manager
# (cm) work, we need to enter into the cm ourselves, and return a dummy
# cm that does nothing on entry and cleans up the xkcd context on exit.
# Additionally, we need to keep a reference to the dummy cm because it
# would otherwise be exited when GC'd.

class dummy_ctx(object):
def __enter__(self):
pass

__exit__ = xkcd_ctx.__exit__

return dummy_ctx()


## Figures ##
Expand Down
7 changes: 5 additions & 2 deletions lib/matplotlib/tests/test_style.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
from __future__ import absolute_import, division, print_function

from collections import OrderedDict
from contextlib import contextmanager
import gc
import os
import shutil
import tempfile
import warnings
from collections import OrderedDict
from contextlib import contextmanager

import pytest

Expand Down Expand Up @@ -163,6 +164,8 @@ def test_xkcd_no_cm():
assert mpl.rcParams["path.sketch"] is None
plt.xkcd()
assert mpl.rcParams["path.sketch"] == (1, 100, 2)
gc.collect()
assert mpl.rcParams["path.sketch"] == (1, 100, 2)


def test_xkcd_cm():
Expand Down