Skip to content

Commit

Permalink
Support tab completion in Jupyter by inserting aliases into the metho…
Browse files Browse the repository at this point in the history
…d signature (#1282)

Add a new insert_alias() function in pygmt/helpers/decorators.py that is used
by the use_alias() decorator to insert aliases into the method signature, to
support tab completion in Jupyter and iPython.

Co-authored-by: Wei Ji <[email protected]>
Co-authored-by: Dongdong Tian <[email protected]>
  • Loading branch information
3 people authored Jun 16, 2021
1 parent 623fe21 commit d7b510f
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions pygmt/helpers/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import functools
import textwrap
import warnings
from inspect import Parameter, signature

import numpy as np
from pygmt.exceptions import GMTInvalidInput
Expand Down Expand Up @@ -322,6 +323,30 @@ def fmt_docstring(module_func):
return module_func


def _insert_alias(module_func, default_value=None):
"""
Function to insert PyGMT long aliases into the signature of a method.
"""

# Get current signature and parameters
sig = signature(module_func)
wrapped_params = list(sig.parameters.values())
kwargs_param = wrapped_params.pop(-1)
# Add new parameters from aliases
for alias in module_func.aliases.values():
if alias not in sig.parameters.keys():
new_param = Parameter(
alias, kind=Parameter.KEYWORD_ONLY, default=default_value
)
wrapped_params = wrapped_params + [new_param]
all_params = wrapped_params + [kwargs_param]
# Update method signature
sig_new = sig.replace(parameters=all_params)
module_func.__signature__ = sig_new

return module_func


def use_alias(**aliases):
"""
Decorator to add aliases to keyword arguments of a function.
Expand Down Expand Up @@ -383,6 +408,8 @@ def new_module(*args, **kwargs):

new_module.aliases = aliases

new_module = _insert_alias(new_module)

return new_module

return alias_decorator
Expand Down

0 comments on commit d7b510f

Please sign in to comment.