8000 Move cbook._define_aliases() to _api.define_aliases() by timhoffm · Pull Request #22411 · matplotlib/matplotlib · GitHub
[go: up one dir, main page]

Skip to content

Move cbook._define_aliases() to _api.define_aliases() #22411

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 1 commit into from
Feb 15, 2022
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
55 changes: 55 additions & 0 deletions lib/matplotlib/_api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,61 @@ def __getattr__(name):
return __getattr__


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

Use as ::

@_api.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 the actual class decorator.
return functools.partial(define_aliases, alias_d)

def make_alias(name): # Enforce a closure over *name*.
@functools.wraps(getattr(cls, 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))

def get_aliased_and_aliases(d):
return {*d, *(alias for aliases in d.values() for alias in aliases)}

preexisting_aliases = getattr(cls, "_alias_map", {})
conflicting = (get_aliased_and_aliases(preexisting_aliases)
& get_aliased_and_aliases(alias_d))
if conflicting:
# Need to decide on conflict resolution policy.
raise NotImplementedError(
f"Parent class already defines conflicting aliases: {conflicting}")
cls._alias_map = {**preexisting_aliases, **alias_d}
return cls


def select_matching_signature(funcs, *args, **kwargs):
"""
Select and call the function that accepts ``*args, **kwargs``.
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/axes/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -537,7 +537,7 @@ def _plot_args(self, tup, kwargs, return_kwargs=False):
return [l[0] for l in result]


@cbook._define_aliases({"facecolor": ["fc"]})
@_api.define_aliases({"facecolor": ["fc"]})
class _AxesBase(martist.Artist):
name = "rectilinear"

Expand Down
55 changes: 0 additions & 55 deletions lib/matplotlib/cbook/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1834,61 +1834,6 @@ def _str_lower_equal(obj, s):
return isinstance(obj, str) 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 the actual class decorator.
return functools.partial(_define_aliases, alias_d)

def make_alias(name): # Enforce a closure over *name*.
@functools.wraps(getattr(cls, 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))

def get_aliased_and_aliases(d):
return {*d, *(alias for aliases in d.values() for alias in aliases)}

preexisting_aliases = getattr(cls, "_alias_map", {})
conflicting = (get_aliased_and_aliases(preexisting_aliases)
& get_aliased_and_aliases(alias_d))
if conflicting:
# Need to decide on conflict resolution policy.
raise NotImplementedError(
f"Parent class already defines conflicting aliases: {conflicting}")
cls._alias_map = {**preexisting_aliases, **alias_d}
return cls


def _array_perimeter(arr):
"""
Get the elements on the perimeter of *arr*.
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

# "color" is excluded; it is a compound setter, and its docstring differs
# in LineCollection.
@cbook._define_aliases({
@_api.define_aliases({
"antialiased": ["antialiaseds", "aa"],
"edgecolor": ["edgecolors", "ec"],
"facecolor": ["facecolors", "fc"],
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/lines.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ def _slice_or_none(in_v, slc):


@docstring.interpd
@cbook._define_aliases({
@_api.define_aliases({
"antialiased": ["aa"],
"color": ["c"],
"drawstyle": ["ds"],
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/patches.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@


@docstring.interpd
@cbook._define_aliases({
@_api.define_aliases({
"antialiased": ["aa"],
"edgecolor": ["ec"],
"facecolor": ["fc"],
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def _get_text_metrics_with_cache_impl(


@docstring.interpd
@cbook._define_aliases({
@_api.define_aliases({
"color": ["c"],
"fontfamily": ["family"],
"fontproperties": ["font", "font_properties"],
Expand Down
2 changes: 1 addition & 1 deletion lib/mpl_toolkits/mplot3d/axes3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@


@docstring.interpd
@cbook._define_aliases({
@_api.define_aliases({
"xlim": ["xlim3d"], "ylim": ["ylim3d"], "zlim": ["zlim3d"]})
class Axes3D(Axes):
"""
Expand Down
0