8
8
import functools
9
9
import textwrap
10
10
import warnings
11
+ from inspect import Parameter , signature
11
12
12
13
import numpy as np
13
14
from pygmt .exceptions import GMTInvalidInput
@@ -322,6 +323,30 @@ def fmt_docstring(module_func):
322
323
return module_func
323
324
324
325
326
+ def _insert_alias (module_func , default_value = None ):
327
+ """
328
+ Function to insert PyGMT long aliases into the signature of a method.
329
+ """
330
+
331
+ # Get current signature and parameters
332
+ sig = signature (module_func )
333
+ wrapped_params = list (sig .parameters .values ())
334
+ kwargs_param = wrapped_params .pop (- 1 )
335
+ # Add new parameters from aliases
336
+ for alias in module_func .aliases .values ():
337
+ if alias not in sig .parameters .keys ():
338
+ new_param = Parameter (
339
+ alias , kind = Parameter .KEYWORD_ONLY , default = default_value
340
+ )
341
+ wrapped_params = wrapped_params + [new_param ]
342
+ all_params = wrapped_params + [kwargs_param ]
343
+ # Update method signature
344
+ sig_new = sig .replace (parameters = all_params )
345
+ module_func .__signature__ = sig_new
346
+
347
+ return module_func
348
+
349
+
325
350
def use_alias (** aliases ):
326
351
"""
327
352
Decorator to add aliases to keyword arguments of a function.
@@ -359,7 +384,7 @@ def use_alias(**aliases):
359
384
Traceback (most recent call last):
360
385
...
361
386
pygmt.exceptions.GMTInvalidInput:
362
- Arguments in short-form (J) and long-form (projection) can't coexist
387
+ Parameters in short-form (J) and long-form (projection) can't coexist.
363
388
"""
364
389
365
390
def alias_decorator (module_func ):
@@ -372,17 +397,26 @@ def new_module(*args, **kwargs):
372
397
"""
373
398
New module that parses and replaces the registered aliases.
374
399
"""
375
- for arg , alias in aliases .items ():
376
- if alias in kwargs and arg in kwargs :
400
+ for short_param , long_alias in aliases .items ():
401
+ if long_alias in kwargs and short_param in kwargs :
377
402
raise GMTInvalidInput (
378
- f"Arguments in short-form ({ arg } ) and long-form ({ alias } ) can't coexist"
403
+ f"Parameters in short-form ({ short_param } ) and "
404
+ f"long-form ({ long_alias } ) can't coexist."
379
405
)
380
- if alias in kwargs :
381
- kwargs [arg ] = kwargs .pop (alias )
406
+ if long_alias in kwargs :
407
+ kwargs [short_param ] = kwargs .pop (long_alias )
408
+ elif short_param in kwargs :
409
+ msg = (
410
+ f"Short-form parameter ({ short_param } ) is not recommended. "
411
+ f"Use long-form parameter '{ long_alias } ' instead."
412
+ )
413
+ warnings .warn (msg , category = SyntaxWarning , stacklevel = 2 )
382
414
return module_func (* args , ** kwargs )
383
415
384
416
new_module .aliases = aliases
385
417
418
+ new_module = _insert_alias (new_module )
419
+
386
420
return new_module
387
421
388
422
return alias_decorator
0 commit comments