8000 Merge pull request #1861 from pelson/find_all_rcs · matplotlib/matplotlib@bc510f3 · GitHub
[go: up one dir, main page]

Skip to content

Commit bc510f3

Browse files
committed
Merge pull request #1861 from pelson/find_all_rcs
Added a find_all method to the RcParams dictionary.
2 parents 3d65613 + d16ab91 commit bc510f3

File tree

4 files changed

+107
-4
lines changed

4 files changed

+107
-4
lines changed

doc/users/whats_new.rst

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,21 @@ used, which, in the case of straight contours was sometimes quite distant
116116
from the requested location. Much more precise label positioning is now
117117
possible.
118118

119+
Quickly find rcParams
120+
---------------------
121+
Phil Elson made it easier to search for rcParameters by passing a
122+
valid regular expression to :func:`matplotlib.RcParams.find_all`.
123+
:class:`matplotlib.RcParams` now also has a pretty repr and str representation
124+
so that search results are printed prettily:
125+
126+
>>> import matplotlib
127+
>>> print(matplotlib.rcParams.find_all('\.size'))
128+
RcParams({'font.size': 12,
129+
'xtick.major.size': 4,
130+
'xtick.minor.size': 2,
131+
'ytick.major.size': 4,
132+
'ytick.minor.size': 2})
133+
119134
.. _whats-new-1-2-2:
120135

121136
new in matplotlib 1.2.2

lib/matplotlib/__init__.py

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -742,8 +742,8 @@ class RcParams(dict):
742742
:mod:`matplotlib.rcsetup`
743743
"""
744744

745-
validate = dict([ (key, converter) for key, (default, converter) in \
746-
defaultParams.iteritems() ])
745+
validate = dict((key, converter) for key, (default, converter) in \
746+
defaultParams.iteritems())
747747
msg_depr = "%s is deprecated and replaced with %s; please use the latter."
748748
msg_depr_ignore = "%s is deprecated and ignored. Use %s"
749749

@@ -774,6 +774,19 @@ def __getitem__(self, key):
774774
key = alt
775775
return dict.__getitem__(self, key)
776776

777+
def __repr__(self):
778+
import pprint
779+
class_name = self.__class__.__name__
780+
indent = len(class_name) + 1
781+
repr_split = pprint.pformat(dict(self), indent=1,
782+
width=80 - indent).split('\n')
783+
repr_indented = ('\n' + ' ' * indent).join(repr_split)
784+
return '{0}({1})'.format(class_name, repr_indented)
785+
786+
def __str__(self):
787+
return '\n'.join('{0}: {1}'.format(k, v)
788+
for k, v in sorted(self.items()))
789+
777790
def keys(self):
778791
"""
779792
Return sorted list of keys.
@@ -786,7 +799,25 @@ def values(self):
786799
"""
787800
Return values in order of sorted keys.
788801
"""
789-
return [self[k] for k in self.iterkeys()]
802+
return [self[k] for k in self.keys()]
803+
804+
def find_all(self, pattern):
805+
"""
806+
Return the subset of this RcParams dictionary whose keys match,
807+
using :func:`re.search`, the given ``pattern``.
808+
809+
.. note::
810+
811+
Changes to the returned dictionary are *not* propagated to
812+
the parent RcParams dictionary.
813+
814+
"""
815+
import re
816+
pattern_re = re.compile(pattern)
817+
return RcParams((key, value)
818+
for key, value in self.items()
819+
if pattern_re.search(key))
820+
790821

791822
def rc_params(fail_on_error=False):
792823
'Return the default params updated from the values in the rc file'

lib/matplotlib/tests/__init__.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
from __future__ import print_function
22
from matplotlib import rcParams, rcdefaults, use
33

4+
import difflib
5+
6+
47
_multiprocess_can_split_ = True
58

9+
610
def setup():
711
use('Agg', warn=False) # use Agg backend for these tests
812

@@ -13,3 +17,19 @@ def setup():
1317
rcParams['font.family'] = 'Bitstream Vera Sans'
1418
rcParams['text.hinting'] = False
1519
rcParams['text.hinting_factor'] = 8
20+
21+
22+
def assert_str_equal(reference_str, test_str,
23+
format_str='String {str1} and {str2} do not match:\n{differences}'):
24+
"""
25+
Assert the two strings are equal. If not, fail and print their diffs using difflib.
26+
27+
"""
28+
if reference_str != test_str:
29+
diff = difflib.unified_diff(reference_str.splitlines(1),
30+
test_str.splitlines(1),
31+
'Reference', 'Test result',
32+
'', '', 0)
33+
raise ValueError(format_str.format(str1=reference_str,
34+
str2=test_str,
35+
differences=''.join(diff)))

lib/matplotlib/tests/test_rcparams.py

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
import os
22

33
import matplotlib as mpl
4+
from matplotlib.tests import assert_str_equal
5+
6+
47
mpl.rc('text', usetex=False)
58
mpl.rc('lines', linewidth=22)
69

@@ -34,5 +37,39 @@ def test_rcparams():
3437
mpl.rcParams['lines.linewidth'] = linewidth
3538

3639

40+
def test_RcParams_class():
41+
rc = mpl.RcParams({'font.cursive': ['Apple Chancery',
42+
'Textile',
43+
'Zapf Chancery',
44+
'cursive'],
45+
'font.family': 'sans-serif',
46+
'font.weight': 'normal',
47+
'font.size': 12})
48+
49+
50+
expected_repr = """
51+
RcParams({'font.cursive': ['Apple Chancery',
52+
'Textile',
53+
'Zapf Chancery',
54+
'cursive'],
55+
'font.family': 'sans-serif',
56+
'font.size': 12,
57+
'font.weight': 'normal'})""".lstrip()
58+
59+
assert_str_equal(expected_repr, repr(rc))
60+
61+
expected_str = """
62+
font.cursive: ['Apple Chancery', 'Textile', 'Zapf Chancery', 'cursive']
63+
font.family: sans-serif
64+
font.size: 12
65+
font.weight: normal""".lstrip()
66+
67+
assert_str_equal(expected_str, str(rc))
68+
69+
# test the find_all functionality
70+
assert ['font.cursive', 'font.size'] == sorted(rc.find_all('i[vz]').keys())
71+
assert ['font.family'] == rc.find_all('family').keys()
72+
3773
if __name__ == '__main__':
38-
test_rcparams()
74+
import nose
75+
nose.runmodule(argv=['-s', '--with-doctest'], exit=False)

0 commit comments

Comments
 (0)
0