|
7 | 7 | """
|
8 | 8 | import functools
|
9 | 9 | import textwrap
|
| 10 | +import warnings |
10 | 11 |
|
11 | 12 | import numpy as np
|
12 | 13 | from pygmt.exceptions import GMTInvalidInput
|
@@ -469,3 +470,65 @@ def remove_bools(kwargs):
|
469 | 470 | else:
|
470 | 471 | new_kwargs[arg] = value
|
471 | 472 | return new_kwargs
|
| 473 | + |
| 474 | + |
| 475 | +def deprecate_parameter(oldname, newname, deprecate_version, remove_version): |
| 476 | + """ |
| 477 | + Decorator to deprecate a parameter. |
| 478 | +
|
| 479 | + Parameters |
| 480 | + ---------- |
| 481 | + oldname : str |
| 482 | + The old, deprecated parameter name. |
| 483 | + newname : str |
| 484 | + The new parameter name. |
| 485 | + deprecate_version : str |
| 486 | + The PyGMT version when the old parameter starts to be deprecated. |
| 487 | + remove_version : str |
| 488 | + The PyGMT version when the old parameter will be fully removed. |
| 489 | +
|
| 490 | + Examples |
| 491 | + -------- |
| 492 | +
|
| 493 | + >>> @deprecate_parameter("sizes", "size", "v0.0.0", "v9.9.9") |
| 494 | + ... @deprecate_parameter("colors", "color", "v0.0.0", "v9.9.9") |
| 495 | + ... def module(size=0, **kwargs): |
| 496 | + ... "A module that prints the arguments it received" |
| 497 | + ... print(f"size={size}, color={kwargs['color']}") |
| 498 | + >>> # new names are supported |
| 499 | + >>> module(size=5.0, color="red") |
| 500 | + size=5.0, color=red |
| 501 | + >>> # old names are supported |
| 502 | + >>> module(sizes=5.0, colors="red") |
| 503 | + size=5.0, color=red |
| 504 | + """ |
| 505 | + |
| 506 | + def deprecator(module_func): |
| 507 | + """ |
| 508 | + The decorator that creates our new function to work with both old and |
| 509 | + new parameters. |
| 510 | + """ |
| 511 | + |
| 512 | + @functools.wraps(module_func) |
| 513 | + def new_module(*args, **kwargs): |
| 514 | + """ |
| 515 | + New module instance that converts old parameters to new parameters. |
| 516 | + """ |
| 517 | + if oldname in kwargs: |
| 518 | + if newname in kwargs: |
| 519 | + raise GMTInvalidInput( |
| 520 | + f"Can't provide both '{newname}' and '{oldname}'" |
| 521 | + ) |
| 522 | + msg = ( |
| 523 | + f"'{oldname}' is deprecated since {deprecate_version} and will" |
| 524 | + f" be removed in {remove_version}; use '{newname}' instead." |
| 525 | + ) |
| 526 | + warnings.simplefilter("always", DeprecationWarning) # turn off filter |
| 527 | + warnings.warn(msg, DeprecationWarning, 2) |
| 528 | + warnings.simplefilter("default", DeprecationWarning) # reset filter |
| 529 | + kwargs[newname] = kwargs.pop(oldname) |
| 530 | + return module_func(*args, **kwargs) |
| 531 | + |
| 532 | + return new_module |
| 533 | + |
| 534 | + return deprecator |
0 commit comments