本文整理汇总了Python中inspect.getargspec方法的典型用法代码示例。如果您正苦于以下问题:Python inspect.getargspec方法的具体用法?Python inspect.getargspec怎么用?Python inspect.getargspec使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类inspect
的用法示例。
在下文中一共展示了inspect.getargspec方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargspec [as 别名]
def __init__(self, docstring, class_name, class_object):
super(NumpyClassDocString, self).__init__(docstring)
self.class_name = class_name
methods = dict((name, func) for name, func
in inspect.getmembers(class_object))
self.has_parameters = False
if '__init__' in methods:
# verify if __init__ is a Python function. If it isn't
# (e.g. the function is implemented in C), getargspec will fail
if not inspect.ismethod(methods['__init__']):
return
args, varargs, keywords, defaults = inspect.getargspec(
methods['__init__'])
if (args and args != ['self']) or varargs or keywords or defaults:
self.has_parameters = True
示例2: register_ranged_hparams
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargspec [as 别名]
def register_ranged_hparams(name=None):
"""Register a RangedHParams set. name defaults to fn name snake-cased."""
def decorator(rhp_fn, registration_name=None):
"""Registers & returns hp_fn with registration_name or default name."""
rhp_name = registration_name or default_name(rhp_fn)
if rhp_name in _RANGED_HPARAMS:
raise LookupError("RangedHParams set %s already registered." % rhp_name)
# Check that the fn takes a single argument
args, varargs, keywords, _ = inspect.getargspec(rhp_fn)
if len(args) != 1 or varargs is not None or keywords is not None:
raise ValueError("RangedHParams set function must take a single "
"argument, the RangedHParams object.")
_RANGED_HPARAMS[rhp_name] = rhp_fn
return rhp_fn
# Handle if decorator was used without parens
if callable(name):
rhp_fn = name
return decorator(rhp_fn, registration_name=default_name(rhp_fn))
return lambda rhp_fn: decorator(rhp_fn, name)
示例3: oneshot
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargspec [as 别名]
def oneshot(equations, *args):
"""
A one-shot calculation.
Args:
equations (callable): coupled-cluster equations;
args (iterable): amplitudes and hamiltonian matrix elements as dicts;
Returns:
Results of the calculation.
"""
input_args = inspect.getargspec(equations).args
fw_args = {}
for i in args:
fw_args.update(i)
# Remove excess arguments from the Hamiltonian
fw_args = {k: v for k, v in fw_args.items() if k in input_args}
# Check missing arguments
missing = set(input_args) - set(fw_args.keys())
if len(missing) > 0:
raise ValueError("Following arguments are missing: {}".format(', '.join(missing)))
return equations(**fw_args)
示例4: usage
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargspec [as 别名]
def usage(error=None):
if error:
print ("Error: " + error)
print ("LGTV Controller")
print ("Author: Karl Lattimer <karl@qdh.org.uk>")
print ("Usage: lgtv <command> [parameter]\n")
print ("Available Commands:")
print (" -i interactive mode")
print (" scan")
print (" auth <host> <tv_name>")
commands = LGTVRemote.getCommands()
for c in commands:
args = getargspec(LGTVRemote.__dict__[c])
if len(args.args) > 1:
a = ' <' + '> <'.join(args.args[1:-1]) + '>'
print (' <tv_name> ' + c + a)
else:
print (' <tv_name> ' + c)
示例5: parseargs
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargspec [as 别名]
def parseargs(command, argv):
args = getargspec(LGTVRemote.__dict__[command])
args = args.args[1:-1]
if len(args) != len(argv):
raise Exception("Argument lengths do not match")
output = {}
for (i, a) in enumerate(args):
if argv[i].lower() == "true":
argv[i] = True
elif argv[i].lower() == "false":
argv[i] = False
try:
f = int(argv[i])
argv[i] = f
except:
try:
f = float(argv[i])
argv[i] = f
except:
pass
output[a] = argv[i]
return output
示例6: usage
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargspec [as 别名]
def usage(error=None):
if error:
print ("Error: " + error)
print ("LGTV Controller")
print ("Author: Karl Lattimer <karl@qdh.org.uk>")
print ("Usage: lgtv <command> [parameter]\n")
print ("Available Commands:")
print (" scan")
print (" auth Hostname/IP Authenticate and exit, creates initial config ~/.lgtv.json")
for c in getCommands(LGTVClient):
print (" " + c, end=" ")
print (" " * (20 - len(c)), end=" ")
args = getargspec(LGTVClient.__dict__[c])
print (' '.join(args.args[1:-1]))
示例7: expects_func_args
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargspec [as 别名]
def expects_func_args(*args):
def _decorator_checker(dec):
@functools.wraps(dec)
def _decorator(f):
base_f = get_wrapped_function(f)
argspec = getargspec(base_f)
if argspec[1] or argspec[2] or set(args) <= set(argspec[0]):
# NOTE (ndipanov): We can't really tell if correct stuff will
# be passed if it's a function with *args or **kwargs so
# we still carry on and hope for the best
return dec(f)
else:
raise TypeError("Decorated function %(f_name)s does not "
"have the arguments expected by the "
"decorator %(d_name)s" %
{'f_name': base_f.__name__,
'd_name': dec.__name__})
return _decorator
return _decorator_checker
示例8: get_argCount
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargspec [as 别名]
def get_argCount(func) -> int:
"""获取函数对象的参数个数
def sum(a,b):
return(a+b)
print(sum.__code__.co_argcount) # 2
#输出的函数参数个数
print(sum.__code__.co_varnames) # ('a', 'b')
#这里会输出函数用到的所有变量名,不只是参数名
print(sum.__defaults__) # None
# 返回参数的初始值
import inspect
inspect.getargspec(sum) #ArgSpec(args=['a', 'b'], varargs=None, keywords=None, defaults=None)
:param func: 函数对象
:return: 函数对象的参数个数
"""
return func.__code__.co_argcount
示例9: _get_check_functions
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargspec [as 别名]
def _get_check_functions(name=None, request=None):
checks = _get_registered_health_checks()
if not checks or (name and name not in checks):
raise StopIteration()
checks = _filter_checks_on_permission(request, checks)
if not checks or (name and name not in checks):
raise PermissionDenied()
for service, func_string in checks.items():
if name and name != service:
continue
if callable(func_string):
check_func = func_string
elif func_string.startswith(('https://', 'http://')):
check_func = _http_healthcheck_func(func_string)
else:
check_func = import_string(func_string)
spec = inspect.getargspec(check_func)
if spec.args == ['request']:
check_func = functools.partial(check_func, request)
yield service, check_func
示例10: version_kwargs
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargspec [as 别名]
def version_kwargs(d):
""" Fix API calls for kwargs dict ``d`` that should have key ``estimator``
"""
argspec = inspect.getargspec(CCDCesque.__init__)
if 'estimator' in argspec.args:
# Spec updated to estimator={object': ..., 'fit': {}}
idx = [i for i, arg in enumerate(argspec.args)
if arg == 'estimator'][0] - 1
if isinstance(argspec.defaults[idx], dict):
return d
else:
d['estimator'] = {'object': d['estimator'], 'fit': {}}
elif 'lm' in argspec.args:
new_key, old_key = 'lm', 'estimator'
d[new_key] = d.pop(old_key)
return d
else:
raise KeyError('Neither "lm" nor "estimator" are keys in '
'CCDCesque.__init__')
示例11: assert_docstring_includes_param_metadata
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargspec [as 别名]
def assert_docstring_includes_param_metadata(thing, path):
if inspect.isclass(thing):
return
docstring = inspect.getdoc(thing)
if not docstring:
return
for arg_name in inspect.getargspec(thing).args:
if arg_name in ("self", "cls"):
continue
if ":param %s:" % arg_name not in docstring:
raise AssertionError(
"Missing :param: for arg %s of %s" % (arg_name, path)
)
if ":type %s:" % arg_name not in docstring:
raise AssertionError(
"Missing :type: for arg %s of %s" % (arg_name, path)
)
示例12: filter_chain
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargspec [as 别名]
def filter_chain(filters, token, func, *args, **kwargs):
if token == -1:
return func()
else:
def _inner_method():
fm = filters[token]
fargs = getargspec(fm)[0]
if len(fargs) == 1:
# Only self arg
result = func()
if result is None:
return fm()
else:
raise IncorrectPluginArg(u'Plugin filter method need a arg to receive parent method result.')
else:
return fm(func if fargs[1] == '__' else func(), *args, **kwargs)
return filter_chain(filters, token - 1, _inner_method, *args, **kwargs)
示例13: _check_signature
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargspec [as 别名]
def _check_signature(self, fn, fn_description, *args, **kwargs):
exception_msg = None
if IS_PYTHON2:
try:
callable_ = fn if hasattr(fn, '__name__') else fn.__call__
inspect.getcallargs(callable_, self, *args, **kwargs)
except TypeError as exc:
spec = inspect.getargspec(callable_)
fn_params = list(spec.args)
exception_msg = str(exc)
else:
signature = inspect.signature(fn)
try:
signature.bind(self, *args, **kwargs)
except TypeError as exc:
fn_params = list(signature.parameters)
exception_msg = str(exc)
if exception_msg:
passed_params = [self] + list(args) + list(kwargs)
raise ValueError("Error adding {} '{}': "
"takes parameters {} but will be called with {} "
"({})".format(
fn, fn_description, fn_params, passed_params, exception_msg))
示例14: ModuleHasValidMainFunction
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargspec [as 别名]
def ModuleHasValidMainFunction(module):
"""Determines if a module has a main function that takes no arguments.
This includes functions that have arguments with defaults that are all
assigned, thus requiring no additional arguments in order to be called.
Args:
module: A types.ModuleType instance.
Returns:
True if the module has a valid, reusable main function; False otherwise.
"""
if hasattr(module, 'main') and type(module.main) is types.FunctionType:
arg_names, var_args, var_kwargs, default_values = inspect.getargspec(
module.main)
if len(arg_names) == 0:
return True
if default_values is not None and len(arg_names) == len(default_values):
return True
return False
示例15: _each_subclass_instantiated_with_mock_args
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargspec [as 别名]
def _each_subclass_instantiated_with_mock_args(self):
"""
This returns an instantiated copy of each subclass of
UpdatingMetadataWrapperBase, passing a MagicMock for each argument on
initialization. This lets us test properties that should hold for all
subclasses.
I don't like having tests depend on this weird metaprogramming, but I'd
rather have this, which generates tests for any future subclasses, than
miss tests for them.
"""
for klaus in UpdatingMetadataWrapperBase.__subclasses__():
# get length of argument list for class init
init_arg_len = len(inspect.getargspec(klaus.__init__)[0])
# args list is one shorter -- argspec includes self
init_args = [MagicMock() for _ in range(init_arg_len - 1)]
yield klaus(*init_args)