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

Skip to content

Declare property aliases in a single place #9475

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 7 commits into from
Mar 15, 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
41 changes: 15 additions & 26 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,17 +48,6 @@

rcParams = matplotlib.rcParams

_alias_map = {'color': ['c'],
'linewidth': ['lw'],
'linestyle': ['ls'],
'facecolor': ['fc'],
'edgecolor': ['ec'],
'markerfacecolor': ['mfc'],
'markeredgecolor': ['mec'],
'markeredgewidth': ['mew'],
'markersize': ['ms'],
}


def _plot_args_replacer(args, data):
if len(args) == 1:
Expand Down Expand Up @@ -1519,7 +1508,7 @@ def plot(self, *args, **kwargs):
self.cla()
lines = []

kwargs = cbook.normalize_kwargs(kwargs, _alias_map)
kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D._alias_map)

for line in self._get_lines(*args, **kwargs):
self.add_line(line)
Expand Down Expand Up @@ -2090,7 +2079,7 @@ def bar(self, *args, **kwargs):
%(Rectangle)s

"""
kwargs = cbook.normalize_kwargs(kwargs, mpatches._patch_alias_map)
kwargs = cbook.normalize_kwargs(kwargs, mpatches.Patch._alias_map)
# this is using the lambdas to do the arg/kwarg unpacking rather
# than trying to re-implement all of that logic our selves.
matchers = [
Expand Down Expand Up @@ -3035,7 +3024,7 @@ def errorbar(self, x, y, yerr=None, xerr=None,
.. [Notes section required for data comment. See #10189.]

"""
kwargs = cbook.normalize_kwargs(kwargs, _alias_map)
kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D._alias_map)
# anything that comes in as 'None', drop so the default thing
# happens down stream
kwargs = {k: v for k, v in kwargs.items() if v is not None}
Expand Down Expand Up @@ -4928,7 +4917,8 @@ def fill(self, *args, **kwargs):
if not self._hold:
self.cla()

kwargs = cbook.normalize_kwargs(kwargs, _alias_map)
# For compatibility(!), get aliases from Line2D rather than Patch.
kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D._alias_map)

patches = []
for poly in self._get_patches_for_fill(*args, **kwargs):
Expand Down Expand Up @@ -5022,12 +5012,11 @@ def fill_between(self, x, y1, y2=0, where=None, interpolate=False,

"""
if not rcParams['_internal.classic_mode']:
color_aliases = mcoll._color_aliases
kwargs = cbook.normalize_kwargs(kwargs, color_aliases)

if not any(c in kwargs for c in ('color', 'facecolors')):
fc = self._get_patches_for_fill.get_next_color()
kwargs['facecolors'] = fc
kwargs = cbook.normalize_kwargs(
kwargs, mcoll.Collection._alias_map)
if not any(c in kwargs for c in ('color', 'facecolor')):
kwargs['facecolor'] = \
self._get_patches_for_fill.get_next_color()

# Handle united data, such as dates
self._process_unit_info(xdata=x, ydata=y1, kwargs=kwargs)
Expand Down Expand Up @@ -5204,12 +5193,12 @@ def fill_betweenx(self, y, x1, x2=0, where=None,

"""
if not rcParams['_internal.classic_mode']:
color_aliases = mcoll._color_aliases
kwargs = cbook.normalize_kwargs(kwargs, color_aliases)
kwargs = cbook.normalize_kwargs(
kwargs, mcoll.Collection._alias_map)
if not any(c in kwargs for c in ('color', 'facecolor')):
kwargs['facecolor'] = \
self._get_patches_for_fill.get_next_color()

if not any(c in kwargs for c in ('color', 'facecolors')):
fc = self._get_patches_for_fill.get_next_color()
kwargs['facecolors'] = fc
# Handle united data, such as dates
self._process_unit_info(ydata=y, xdata=x1, kwargs=kwargs)
self._process_unit_info(xdata=x2)
Expand Down
46 changes: 46 additions & 0 deletions lib/matplotlib/cbook/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2803,3 +2803,49 @@ def _str_lower_equal(obj, s):
cannot be used in a boolean context.
"""
return isinstance(obj, six.string_types) and obj.lower() == s


def _define_aliases(alias_d, cls=None):
"""Class decorator for defining property aliases.

Use as ::

@cbook._define_aliases({"property": ["alias", ...], ...})
class C: ...

For each property, if the corresponding ``get_property`` is defined in the
class so far, an alias named ``get_alias`` will be defined; the same will
be done for setters. If neither the getter nor the setter exists, an
exception will be raised.

The alias map is stored as the ``_alias_map`` attribute on the class and
can be used by `~.normalize_kwargs` (which assumes that higher priority
aliases come last).
"""
if cls is None:
return functools.partial(_define_aliases, alias_d)

def make_alias(name): # Enforce a closure over *name*.
def method(self, *args, **kwargs):
return getattr(self, name)(*args, **kwargs)
return method

for prop, aliases in alias_d.items():
exists = False
for prefix in ["get_", "set_"]:
if prefix + prop in vars(cls):
exists = True
for alias in aliases:
method = make_alias(prefix + prop)
method.__name__ = prefix + alias
method.__doc__ = "alias for `{}`".format(prefix + prop)
setattr(cls, prefix + alias, method)
if not exists:
raise ValueError(
"Neither getter nor setter exists for {!r}".format(prop))

if hasattr(cls, "_alias_map"):
# Need to decide on conflict resolution policy.
raise NotImplementedError("Parent class already defines aliases")
cls._alias_map = alias_d
return cls
65 changes: 15 additions & 50 deletions lib/matplotlib/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@
they are meant to be fast for common use cases (e.g., a large set of solid
line segemnts)
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from __future__ import absolute_import, division, print_function

import warnings

Expand All @@ -29,10 +28,13 @@
CIRCLE_AREA_FACTOR = 1.0 / np.sqrt(np.pi)


_color_aliases = {'facecolors': ['facecolor'],
'edgecolors': ['edgecolor']}


@cbook._define_aliases({
"antialiased": ["antialiaseds"],
"edgecolor": ["edgecolors"],
"facecolor": ["facecolors"],
"linestyle": ["linestyles", "dashes"],
"linewidth": ["linewidths", "lw"],
Copy link
Contributor

@eric-wieser eric-wieser Jan 2, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not sets, instead of lists? Duplicates wouldn't make any sense here. (edit: because normalize_kwargs requires it to be so)

})
class Collection(artist.Artist, cm.ScalarMappable):
"""
Base class for Collections. Must be subclassed to be usable.
Expand Down Expand Up @@ -505,14 +507,6 @@ def set_linewidth(self, lw):
self._us_lw, self._us_linestyles)
self.stale = True

def set_linewidths(self, lw):
"""alias for set_linewidth"""
return self.set_linewidth(lw)

def set_lw(self, lw):
"""alias for set_linewidth"""
return self.set_linewidth(lw)

def set_linestyle(self, ls):
"""
Set the linestyle(s) for the collection.
Expand Down Expand Up @@ -640,14 +634,6 @@ def _bcast_lwls(linewidths, dashes):

return linewidths, dashes

def set_linestyles(self, ls):
"""alias for set_linestyle"""
return self.set_linestyle(ls)

def set_dashes(self, ls):
"""alias for set_linestyle"""
return self.set_linestyle(ls)

def set_antialiased(self, aa):
"""
Set the antialiasing state for rendering.
Expand All @@ -659,10 +645,6 @@ def set_antialiased(self, aa):
self._antialiaseds = np.atleast_1d(np.asarray(aa, bool))
self.stale = True

def set_antialiaseds(self, aa):
"""alias for set_antialiased"""
return self.set_antialiased(aa)

def set_color(self, c):
"""
Set both the edgecolor and the facecolor.
Expand Down Expand Up @@ -704,21 +686,15 @@ def set_facecolor(self, c):
self._original_facecolor = c
self._set_facecolor(c)

def set_facecolors(self, c):
"""alias for set_facecolor"""
return self.set_facecolor(c)

def get_facecolor(self):
return self._facecolors
get_facecolors = get_facecolor

def get_edgecolor(self):
if (isinstance(self._edgecolors, six.string_types)
and self._edgecolors == str('face')):
return self.get_facecolors()
else:
return self._edgecolors
get_edgecolors = get_edgecolor

def _set_edgecolor(self, c):
set_hatch_color = True
Expand Down Expand Up @@ -764,10 +740,6 @@ def set_edgecolor(self, c):
self._original_edgecolor = c
self._set_edgecolor(c)

def set_edgecolors(self, c):
"""alias for set_edgecolor"""
return self.set_edgecolor(c)

def set_alpha(self, alpha):
"""
Set the alpha tranparencies of the collection. *alpha* must be
Expand All @@ -785,13 +757,11 @@ def set_alpha(self, alpha):
self._set_facecolor(self._original_facecolor)
self._set_edgecolor(self._original_edgecolor)

def get_linewidths(self):
def get_linewidth(self):
return self._linewidths
get_linewidth = get_linewidths

def get_linestyles(self):
def get_linestyle(self):
return self._linestyles
get_dashes = get_linestyle = get_linestyles

def update_scalarmappable(self):
"""
Expand Down Expand Up @@ -836,6 +806,7 @@ def update_from(self, other):
# self.update_dict = other.update_dict # do we need to copy this? -JJL
self.stale = True


# these are not available for the object inspector until after the
# class is built so we define an initial set here for the init
# function and they will be overridden after object defn
Expand Down Expand Up @@ -1556,17 +1527,11 @@ def set_lineoffset(self, lineoffset):
self._lineoffset = lineoffset

def get_linewidth(self):
'''
get the width of the lines used to mark each event
'''
return self.get_linewidths()[0]
"""Get the width of the lines used to mark each event."""
return super(EventCollection, self).get_linewidth()[0]

def get_linestyle(self):
'''
get the style of the lines used to mark each event
[ 'solid' | 'dashed' | 'dashdot' | 'dotted' ]
'''
return self.get_linestyles()
def get_linewidths(self):
return super(EventCollection, self).get_linewidth()

def get_color(self):
'''
Expand Down
Loading