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

Skip to content

Commit f8d2894

Browse files
committed
Updated RcParams.find_all to use re. Added a str and repr for RcParams & added some tests.
1 parent c8fae15 commit f8d2894

4 files changed

Lines changed: 92 additions & 7 deletions

File tree

doc/users/whats_new.rst

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

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

115130
new in matplotlib 1.2.2

lib/matplotlib/__init__.py

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -706,8 +706,8 @@ class RcParams(dict):
706706
:mod:`matplotlib.rcsetup`
707707
"""
708708

709-
validate = dict([ (key, converter) for key, (default, converter) in \
710-
defaultParams.iteritems() ])
709+
validate = dict((key, converter) for key, (default, converter) in \
710+
defaultParams.iteritems())
711711
msg_depr = "%s is deprecated and replaced with %s; please use the latter."
712712
msg_depr_ignore = "%s is deprecated and ignored. Use %s"
713713

@@ -738,6 +738,17 @@ def __getitem__(self, key):
738738
key = alt
739739
return dict.__getitem__(self, key)
740740

741+
def __repr__(self):
742+
import pprint
743+
class_name = self.__class__.__name__
744+
indent = len(class_name) + 1
745+
repr_split = pprint.pformat(dict(self), indent=1, width=80 - indent).split('\n')
746+
repr_indented = ('\n' + ' ' * indent).join(repr_split)
747+
return '{}({})'.format(class_name, repr_indented)
748+
749+
def __str__(self):
750+
return '\n'.join('{}: {}'.format(k, v) for k, v in sorted(self.items()))
751+
741752
def keys(self):
742753
"""
743754
Return sorted list of keys.
@@ -750,22 +761,24 @@ def values(self):
750761
"""
751762
Return values in order of sorted keys.
752763
"""
753-
return [self[k] for k in self.iterkeys()]
764+
return [self[k] for k in self.keys()]
754765

755-
def find_all(self, key_contains):
766+
def find_all(self, pattern):
756767
"""
757768
Return the subset of this RcParams dictionary for which the given
758-
``key_contains`` string is found somewhere in the key.
769+
``pattern`` string is found, by :func:`re.search`, somewhere in the key.
759770
760771
.. note::
761772
762773
Changes to the returned dictionary are *not* propagated to
763774
the parent RcParams dictionary.
764775
765776
"""
777+
import re
778+
pattern_re = re.compile(pattern)
766779
return RcParams((key, value)
767780
for key, value in self.items()
768-
if key_contains in key)
781+
if pattern_re.search(key))
769782

770783

771784
def rc_params(fail_on_error=False):

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)