Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 7769b29

Browse files
committed
Add style context manager and tests
1 parent 455b54c commit 7769b29

File tree

2 files changed

+100
-5
lines changed

2 files changed

+100
-5
lines changed

lib/matplotlib/style/core.py

Lines changed: 39 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,26 +3,30 @@
33
44
``use``
55
Select style sheet to override the current matplotlib settings.
6+
``context``
7+
Context manager to use a style sheet temporarily.
68
``available``
79
List available style sheets.
810
``library``
911
A dictionary of style names and matplotlib settings.
1012
"""
1113
import os
1214
import re
15+
import contextlib
1316

1417
import numpy as np
1518
import matplotlib as mpl
1619

1720

18-
__all__ = ['use', 'available', 'library']
21+
__all__ = ['use', 'context', 'available', 'library', 'reload_library']
1922

2023

2124
_here = os.path.abspath(os.path.dirname(__file__))
2225
BASE_LIBRARY_PATH = os.path.join(_here, 'stylelib')
2326
# Users may want multiple library paths, so store a list of paths.
2427
USER_LIBRARY_PATHS = [os.path.join('~', '.matplotlib', 'stylelib')]
25-
STYLE_FILE_PATTERN = re.compile('([\S]+).style$')
28+
STYLE_EXTENSION = 'style'
29+
STYLE_FILE_PATTERN = re.compile('([\S]+).%s$' % STYLE_EXTENSION)
2630

2731

2832
def is_style_file(filename):
@@ -31,7 +35,7 @@ def is_style_file(filename):
3135

3236

3337
def use(name):
34-
"""Use matplotlib rc parameters from a pre-defined name or from a file.
38+
"""Use matplotlib style settings from a known style sheet or from a file.
3539
3640
Parameters
3741
----------
@@ -55,6 +59,28 @@ def use(name):
5559
mpl.rcParams.update(library[style])
5660

5761

62+
@contextlib.contextmanager
63+
def context(name, after_reset=False):
64+
"""Context manager for using style settings temporarily.
65+
66+
Parameters
67+
----------
68+
name : str or list of str
69+
Name of style or path/URL to a style file. For a list of available
70+
style names, see `style.available`. If given a list, each style is
71+
applied from first to last in the list.
72+
after_reset : bool
73+
If True, apply style after resetting settings to their defaults;
74+
otherwise, apply style on top of the current settings.
75+
"""
76+
initial_settings = mpl.rcParams.copy()
77+
if after_reset:
78+
mpl.rcdefaults()
79+
use(name)
80+
yield
81+
mpl.rcParams.update(initial_settings)
82+
83+
5884
def load_base_library():
5985
"""Load style library defined in this package."""
6086
library = dict()
@@ -114,5 +140,13 @@ def update_nested_dict(main_dict, new_dict):
114140
# Load style library
115141
# ==================
116142
_base_library = load_base_library()
117-
library = update_user_library(_base_library)
118-
available = library.keys()
143+
144+
library = None
145+
available = []
146+
147+
def reload_library():
148+
"""Reload style library."""
149+
global library, available
150+
library = update_user_library(_base_library)
151+
available[:] = library.keys()
152+
reload_library()
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import os
2+
import shutil
3+
import tempfile
4+
from contextlib import contextmanager
5+
6+
import matplotlib as mpl
7+
from matplotlib import style
8+
from matplotlib.style.core import USER_LIBRARY_PATHS, STYLE_EXTENSION
9+
10+
11+
PARAM = 'image.cmap'
12+
VALUE = 'pink'
13+
DUMMY_SETTINGS = {PARAM: VALUE}
14+
15+
16+
@contextmanager
17+
def temp_style(style_name, settings=None):
18+
"""Context manager to create a style sheet in a temporary directory."""
19+
settings = DUMMY_SETTINGS
20+
temp_file = '%s.%s' % (style_name, STYLE_EXTENSION)
21+
22+
# Write style settings to file in the temp directory.
23+
tempdir = tempfile.mkdtemp()
24+
with open(os.path.join(tempdir, temp_file), 'w') as f:
25+
for k, v in settings.iteritems():
26+
f.write('%s: %s' % (k, v))
27+
28+
# Add temp directory to style path and reload so we can access this style.
29+
USER_LIBRARY_PATHS.append(tempdir)
30+
style.reload_library()
31+
32+
try:
33+
yield
34+
finally:
35+
shutil.rmtree(tempdir)
36+
37+
38+
def test_available():
39+
with temp_style('_test_', DUMMY_SETTINGS):
40+
assert '_test_' in style.available
41+
42+
43+
def test_use():
44+
mpl.rcParams[PARAM] = 'gray'
45+
with temp_style('test', DUMMY_SETTINGS):
46+
style.use('test')
47+
assert mpl.rcParams[PARAM] == VALUE
48+
49+
50+
def test_context():
51+
mpl.rcParams[PARAM] = 'gray'
52+
with temp_style('test', DUMMY_SETTINGS):
53+
with style.context('test'):
54+
assert mpl.rcParams[PARAM] == VALUE
55+
# Check that this value is reset after the exiting the context.
56+
assert mpl.rcParams[PARAM] == 'gray'
57+
58+
59+
if __name__ == '__main__':
60+
from numpy import testing
61+
testing.run_module_suite()

0 commit comments

Comments
 (0)