2015-06-11 05:24:04 +08:00
|
|
|
import inspect
|
|
|
|
|
|
|
|
|
|
|
|
def get_func_args(func):
|
|
|
|
sig = inspect.signature(func)
|
|
|
|
return [
|
|
|
|
arg_name for arg_name, param in sig.parameters.items()
|
|
|
|
if param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
|
|
|
|
]
|
|
|
|
|
|
|
|
|
2014-10-31 03:45:01 +08:00
|
|
|
def get_func_full_args(func):
|
|
|
|
"""
|
|
|
|
Return a list of (argument name, default value) tuples. If the argument
|
|
|
|
does not have a default value, omit it in the tuple. Arguments such as
|
|
|
|
*args and **kwargs are also included.
|
|
|
|
"""
|
|
|
|
sig = inspect.signature(func)
|
|
|
|
args = []
|
|
|
|
for arg_name, param in sig.parameters.items():
|
|
|
|
name = arg_name
|
|
|
|
# Ignore 'self'
|
|
|
|
if name == 'self':
|
|
|
|
continue
|
|
|
|
if param.kind == inspect.Parameter.VAR_POSITIONAL:
|
|
|
|
name = '*' + name
|
|
|
|
elif param.kind == inspect.Parameter.VAR_KEYWORD:
|
|
|
|
name = '**' + name
|
|
|
|
if param.default != inspect.Parameter.empty:
|
|
|
|
args.append((name, param.default))
|
|
|
|
else:
|
|
|
|
args.append((name,))
|
|
|
|
return args
|
|
|
|
|
|
|
|
|
2015-06-11 05:24:04 +08:00
|
|
|
def func_accepts_kwargs(func):
|
|
|
|
return any(
|
|
|
|
p for p in inspect.signature(func).parameters.values()
|
|
|
|
if p.kind == p.VAR_KEYWORD
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2014-10-31 03:45:01 +08:00
|
|
|
def func_accepts_var_args(func):
|
|
|
|
"""
|
|
|
|
Return True if function 'func' accepts positional arguments *args.
|
|
|
|
"""
|
|
|
|
return any(
|
|
|
|
p for p in inspect.signature(func).parameters.values()
|
|
|
|
if p.kind == p.VAR_POSITIONAL
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2018-08-07 11:12:51 +08:00
|
|
|
def method_has_no_args(meth):
|
|
|
|
"""Return True if a method only accepts 'self'."""
|
2018-08-07 11:12:51 +08:00
|
|
|
count = len([
|
2018-08-07 11:12:51 +08:00
|
|
|
p for p in inspect.signature(meth).parameters.values()
|
2014-10-31 03:45:01 +08:00
|
|
|
if p.kind == p.POSITIONAL_OR_KEYWORD
|
2018-08-07 11:12:51 +08:00
|
|
|
])
|
|
|
|
return count == 0 if inspect.ismethod(meth) else count == 1
|
2015-06-11 05:24:04 +08:00
|
|
|
|
|
|
|
|
|
|
|
def func_supports_parameter(func, parameter):
|
2016-12-01 18:38:01 +08:00
|
|
|
return parameter in inspect.signature(func).parameters
|