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

Skip to content

Commit b083c2a

Browse files
authored
Merge pull request #9475 from anntzer/unify-aliases
Declare property aliases in a single place
2 parents b1f5c43 + 473590c commit b083c2a

File tree

7 files changed

+120
-278
lines changed

7 files changed

+120
-278
lines changed

lib/matplotlib/axes/_axes.py

Lines changed: 15 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -49,17 +49,6 @@
4949

5050
rcParams = matplotlib.rcParams
5151

52-
_alias_map = {'color': ['c'],
53-
'linewidth': ['lw'],
54-
'linestyle': ['ls'],
55-
'facecolor': ['fc'],
56-
'edgecolor': ['ec'],
57-
'markerfacecolor': ['mfc'],
58-
'markeredgecolor': ['mec'],
59-
'markeredgewidth': ['mew'],
60-
'markersize': ['ms'],
61-
}
62-
6352

6453
def _plot_args_replacer(args, data):
6554
if len(args) == 1:
@@ -1524,7 +1513,7 @@ def plot(self, *args, **kwargs):
15241513
self.cla()
15251514
lines = []
15261515

1527-
kwargs = cbook.normalize_kwargs(kwargs, _alias_map)
1516+
kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D._alias_map)
15281517

15291518
for line in self._get_lines(*args, **kwargs):
15301519
self.add_line(line)
@@ -2121,7 +2110,7 @@ def bar(self, *args, **kwargs):
21212110
%(Rectangle)s
21222111
21232112
"""
2124-
kwargs = cbook.normalize_kwargs(kwargs, mpatches._patch_alias_map)
2113+
kwargs = cbook.normalize_kwargs(kwargs, mpatches.Patch._alias_map)
21252114
# this is using the lambdas to do the arg/kwarg unpacking rather
21262115
# than trying to re-implement all of that logic our selves.
21272116
matchers = [
@@ -3065,7 +3054,7 @@ def errorbar(self, x, y, yerr=None, xerr=None,
30653054
.. [Notes section required for data comment. See #10189.]
30663055
30673056
"""
3068-
kwargs = cbook.normalize_kwargs(kwargs, _alias_map)
3057+
kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D._alias_map)
30693058
# anything that comes in as 'None', drop so the default thing
30703059
# happens down stream
30713060
kwargs = {k: v for k, v in kwargs.items() if v is not None}
@@ -4953,7 +4942,8 @@ def fill(self, *args, **kwargs):
49534942
if not self._hold:
49544943
self.cla()
49554944

4956-
kwargs = cbook.normalize_kwargs(kwargs, _alias_map)
4945+
# For compatibility(!), get aliases from Line2D rather than Patch.
4946+
kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D._alias_map)
49574947

49584948
patches = []
49594949
for poly in self._get_patches_for_fill(*args, **kwargs):
@@ -5049,12 +5039,11 @@ def fill_between(self, x, y1, y2=0, where=None, interpolate=False,
50495039
50505040
"""
50515041
if not rcParams['_internal.classic_mode']:
5052-
color_aliases = mcoll._color_aliases
5053-
kwargs = cbook.normalize_kwargs(kwargs, color_aliases)
5054-
5055-
if not any(c in kwargs for c in ('color', 'facecolors')):
5056-
fc = self._get_patches_for_fill.get_next_color()
5057-
kwargs['facecolors'] = fc
5042+
kwargs = cbook.normalize_kwargs(
5043+
kwargs, mcoll.Collection._alias_map)
5044+
if not any(c in kwargs for c in ('color', 'facecolor')):
5045+
kwargs['facecolor'] = \
5046+
self._get_patches_for_fill.get_next_color()
50585047

50595048
# Handle united data, such as dates
50605049
self._process_unit_info(xdata=x, ydata=y1, kwargs=kwargs)
@@ -5233,12 +5222,12 @@ def fill_betweenx(self, y, x1, x2=0, where=None,
52335222
52345223
"""
52355224
if not rcParams['_internal.classic_mode']:
5236-
color_aliases = mcoll._color_aliases
5237-
kwargs = cbook.normalize_kwargs(kwargs, color_aliases)
5225+
kwargs = cbook.normalize_kwargs(
5226+
kwargs, mcoll.Collection._alias_map)
5227+
if not any(c in kwargs for c in ('color', 'facecolor')):
5228+
kwargs['facecolor'] = \
5229+
self._get_patches_for_fill.get_next_color()
52385230

5239-
if not any(c in kwargs for c in ('color', 'facecolors')):
5240-
fc = self._get_patches_for_fill.get_next_color()
5241-
kwargs['facecolors'] = fc
52425231
# Handle united data, such as dates
52435232
self._process_unit_info(ydata=y, xdata=x1, kwargs=kwargs)
52445233
self._process_unit_info(xdata=x2)

lib/matplotlib/cbook/__init__.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2022,3 +2022,49 @@ def _str_lower_equal(obj, s):
20222022
cannot be used in a boolean context.
20232023
"""
20242024
return isinstance(obj, six.string_types) and obj.lower() == s
2025+
2026+
2027+
def _define_aliases(alias_d, cls=None):
2028+
"""Class decorator for defining property aliases.
2029+
2030+
Use as ::
2031+
2032+
@cbook._define_aliases({"property": ["alias", ...], ...})
2033+
class C: ...
2034+
2035+
For each property, if the corresponding ``get_property`` is defined in the
2036+
class so far, an alias named ``get_alias`` will be defined; the same will
2037+
be done for setters. If neither the getter nor the setter exists, an
2038+
exception will be raised.
2039+
2040+
The alias map is stored as the ``_alias_map`` attribute on the class and
2041+
can be used by `~.normalize_kwargs` (which assumes that higher priority
2042+
aliases come last).
2043+
"""
2044+
if cls is None:
2045+
return functools.partial(_define_aliases, alias_d)
2046+
2047+
def make_alias(name): # Enforce a closure over *name*.
2048+
def method(self, *args, **kwargs):
2049+
return getattr(self, name)(*args, **kwargs)
2050+
return method
2051+
2052+
for prop, aliases in alias_d.items():
2053+
exists = False
2054+
for prefix in ["get_", "set_"]:
2055+
if prefix + prop in vars(cls):
2056+
exists = True
2057+
for alias in aliases:
2058+
method = make_alias(prefix + prop)
2059+
method.__name__ = prefix + alias
2060+
method.__doc__ = "alias for `{}`".format(prefix + prop)
2061+
setattr(cls, prefix + alias, method)
2062+
if not exists:
2063+
raise ValueError(
2064+
"Neither getter nor setter exists for {!r}".format(prop))
2065+
2066+
if hasattr(cls, "_alias_map"):
2067+
# Need to decide on conflict resolution policy.
2068+
raise NotImplementedError("Parent class already defines aliases")
2069+
cls._alias_map = alias_d
2070+
return cls

lib/matplotlib/collections.py

Lines changed: 15 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,7 @@
88
they are meant to be fast for common use cases (e.g., a large set of solid
99
line segemnts)
1010
"""
11-
from __future__ import (absolute_import, division, print_function,
12-
unicode_literals)
11+
from __future__ import absolute_import, division, print_function
1312

1413
import warnings
1514

@@ -31,10 +30,13 @@
3130
CIRCLE_AREA_FACTOR = 1.0 / np.sqrt(np.pi)
3231

3332

34-
_color_aliases = {'facecolors': ['facecolor'],
35-
'edgecolors': ['edgecolor']}
36-
37-
33+
@cbook._define_aliases({
34+
"antialiased": ["antialiaseds"],
35+
"edgecolor": ["edgecolors"],
36+
"facecolor": ["facecolors"],
37+
"linestyle": ["linestyles", "dashes"],
38+
"linewidth": ["linewidths", "lw"],
39+
})
3840
class Collection(artist.Artist, cm.ScalarMappable):
3941
"""
4042
Base class for Collections. Must be subclassed to be usable.
@@ -507,14 +509,6 @@ def set_linewidth(self, lw):
507509
self._us_lw, self._us_linestyles)
508510
self.stale = True
509511

510-
def set_linewidths(self, lw):
511-
"""alias for set_linewidth"""
512-
return self.set_linewidth(lw)
513-
514-
def set_lw(self, lw):
515-
"""alias for set_linewidth"""
516-
return self.set_linewidth(lw)
517-
518512
def set_linestyle(self, ls):
519513
"""
520514
Set the linestyle(s) for the collection.
@@ -642,14 +636,6 @@ def _bcast_lwls(linewidths, dashes):
642636

643637
return linewidths, dashes
644638

645-
def set_linestyles(self, ls):
646-
"""alias for set_linestyle"""
647-
return self.set_linestyle(ls)
648-
649-
def set_dashes(self, ls):
650-
"""alias for set_linestyle"""
651-
return self.set_linestyle(ls)
652-
653639
def set_antialiased(self, aa):
654640
"""
655641
Set the antialiasing state for rendering.
@@ -661,10 +647,6 @@ def set_antialiased(self, aa):
661647
self._antialiaseds = np.atleast_1d(np.asarray(aa, bool))
662648
self.stale = True
663649

664-
def set_antialiaseds(self, aa):
665-
"""alias for set_antialiased"""
666-
return self.set_antialiased(aa)
667-
668650
def set_color(self, c):
669651
"""
670652
Set both the edgecolor and the facecolor.
@@ -706,21 +688,15 @@ def set_facecolor(self, c):
706688
self._original_facecolor = c
707689
self._set_facecolor(c)
708690

709-
def set_facecolors(self, c):
710-
"""alias for set_facecolor"""
711-
return self.set_facecolor(c)
712-
713691
def get_facecolor(self):
714692
return self._facecolors
715-
get_facecolors = get_facecolor
716693

717694
def get_edgecolor(self):
718695
if (isinstance(self._edgecolors, six.string_types)
719696
and self._edgecolors == str('face')):
720697
return self.get_facecolors()
721698
else:
722699
return self._edgecolors
723-
get_edgecolors = get_edgecolor
724700

725701
def _set_edgecolor(self, c):
726702
set_hatch_color = True
@@ -766,10 +742,6 @@ def set_edgecolor(self, c):
766742
self._original_edgecolor = c
767743
self._set_edgecolor(c)
768744

769-
def set_edgecolors(self, c):
770-
"""alias for set_edgecolor"""
771-
return self.set_edgecolor(c)
772-
773745
def set_alpha(self, alpha):
774746
"""
775747
Set the alpha tranparencies of the collection. *alpha* must be
@@ -787,13 +759,11 @@ def set_alpha(self, alpha):
787759
self._set_facecolor(self._original_facecolor)
788760
self._set_edgecolor(self._original_edgecolor)
789761

790-
def get_linewidths(self):
762+
def get_linewidth(self):
791763
return self._linewidths
792-
get_linewidth = get_linewidths
793764

794-
def get_linestyles(self):
765+
def get_linestyle(self):
795766
return self._linestyles
796-
get_dashes = get_linestyle = get_linestyles
797767

798768
def update_scalarmappable(self):
799769
"""
@@ -838,6 +808,7 @@ def update_from(self, other):
838808
# self.update_dict = other.update_dict # do we need to copy this? -JJL
839809
self.stale = True
840810

811+
841812
# these are not available for the object inspector until after the
842813
# class is built so we define an initial set here for the init
843814
# function and they will be overridden after object defn
@@ -1558,17 +1529,11 @@ def set_lineoffset(self, lineoffset):
15581529
self._lineoffset = lineoffset
15591530

15601531
def get_linewidth(self):
1561-
'''
1562-
get the width of the lines used to mark each event
1563-
'''
1564-
return self.get_linewidths()[0]
1532+
"""Get the width of the lines used to mark each event."""
1533+
return super(EventCollection, self).get_linewidth()[0]
15651534

1566-
def get_linestyle(self):
1567-
'''
1568-
get the style of the lines used to mark each event
1569-
[ 'solid' | 'dashed' | 'dashdot' | 'dotted' ]
1570-
'''
1571-
return self.get_linestyles()
1535+
def get_linewidths(self):
1536+
return super(EventCollection, self).get_linewidth()
15721537

15731538
def get_color(self):
15741539
'''

0 commit comments

Comments
 (0)