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

Skip to content

Commit 5c6b096

Browse files
committed
cbook._rename_parameter.
1 parent a4e3de2 commit 5c6b096

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

lib/matplotlib/cbook/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@
3232

3333
import matplotlib
3434
from .deprecation import (
35-
mplDeprecation, deprecated, warn_deprecated, MatplotlibDeprecationWarning)
35+
deprecated, warn_deprecated, _rename_parameter,
36+
MatplotlibDeprecationWarning, mplDeprecation)
3637

3738

3839
@deprecated("3.0")

lib/matplotlib/cbook/deprecation.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,3 +258,51 @@ def wrapper(*args, **kwargs):
258258
return finalize(wrapper, new_doc)
259259

260260
return deprecate
261+
262+
263+
def _rename_parameter(since, old, new, func=None):
264+
"""
265+
Decorator indicating that parameter *old* of *func* is renamed to *new*.
266+
267+
The actual implementation of *func* should use *new*, not *old*. If *old*
268+
is passed to *func*, a DeprecationWarning is emitted, and its value is
269+
used, even if *new* is also passed by keyword (this is to simplify pyplot
270+
wrapper functions, which always pass *new* explicitly to the Axes method).
271+
If *new* is also passed but positionally, a TypeError will be raised by the
272+
underlying function during argument binding.
273+
274+
Examples
275+
--------
276+
277+
::
278+
@_rename_parameter("3.1", "bad_name", "good_name")
279+
def func(good_name): ...
280+
"""
281+
282+
if func is None:
283+
return functools.partial(_rename_parameter, since, old, new)
284+
285+
signature = inspect.signature(func)
286+
assert old not in signature.parameters, (
287+
f"Matplotlib internal error: {old!r} cannot be a parameter for "
288+
"{func.__name__}()")
289+
assert new in signature.parameters, (
290+
f"Matplotlib internal error: {new!r} must be a parameter for "
291+
"{func.__name__}()")
292+
293+
@functools.wraps(func)
294+
def wrapper(*args, **kwargs):
295+
if old in kwargs:
296+
warn_deprecated(
297+
since, message=f"The {old!r} parameter of {func.__name__}() "
298+
f"has been renamed {new!r} since {since}; support for the old "
299+
f"name will be dropped %(removal)s.")
300+
kwargs[new] = kwargs.pop(old)
301+
return func(*args, **kwargs)
302+
303+
# wrapper() must keep the same documented signature as func(): if we
304+
# instead made both *old* and *new* appear in wrapper()'s signature, they
305+
# would both show up in the pyplot function for an Axes method as well and
306+
# pyplot would explicitly pass both arguments to the Axes method.
307+
308+
return wrapper

0 commit comments

Comments
 (0)