本文整理汇总了Python中inspect.ArgSpec方法的典型用法代码示例。如果您正苦于以下问题:Python inspect.ArgSpec方法的具体用法?Python inspect.ArgSpec怎么用?Python inspect.ArgSpec使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类inspect
的用法示例。
在下文中一共展示了inspect.ArgSpec方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _getargspec_py23
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import ArgSpec [as 别名]
def _getargspec_py23(func):
"""_getargspec_py23(function) -> named tuple ArgSpec(args, varargs, keywords,
defaults)
Identical to inspect.getargspec() in python2, but uses
inspect.getfullargspec() for python3 behind the scenes to avoid
DeprecationWarning.
>>> def f(a, b=2, *ar, **kw):
... pass
>>> _getargspec_py23(f)
ArgSpec(args=['a', 'b'], varargs='ar', keywords='kw', defaults=(2,))
"""
if six.PY2:
return inspect.getargspec(func)
return inspect.ArgSpec(*inspect.getfullargspec(func)[:4])
示例2: getargspec
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import ArgSpec [as 别名]
def getargspec( # pylint: disable=inconsistent-return-statements
fn
): # type: (Callable) -> inspect.ArgSpec
"""Get the names and default values of a function's arguments.
Args:
fn (function): a function
Returns:
`inspect.ArgSpec`: A collections.namedtuple with the following attributes:
* Args:
args (list): a list of the argument names (it may contain nested lists).
varargs (str): name of the * argument or None.
keywords (str): names of the ** argument or None.
defaults (tuple): an n-tuple of the default values of the last n arguments.
"""
if six.PY2:
return inspect.getargspec(fn) # pylint: disable=deprecated-method
elif six.PY3:
full_arg_spec = inspect.getfullargspec(fn)
return inspect.ArgSpec(
full_arg_spec.args, full_arg_spec.varargs, full_arg_spec.varkw, full_arg_spec.defaults
)
示例3: getargspec
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import ArgSpec [as 别名]
def getargspec(func):
"""Variation of inspect.getargspec that works for more functions.
This function works for Cythonized, non-cpdef functions, which expose argspec information but
are not accepted by getargspec. It also works for Python 3 functions that use annotations, which
are simply ignored. However, keyword-only arguments are not supported.
"""
if inspect.ismethod(func):
func = func.__func__
# Cythonized functions have a .__code__, but don't pass inspect.isfunction()
try:
code = func.__code__
except AttributeError:
raise TypeError("{!r} is not a Python function".format(func))
if hasattr(code, "co_kwonlyargcount") and code.co_kwonlyargcount > 0:
raise ValueError("keyword-only arguments are not supported by getargspec()")
args, varargs, varkw = inspect.getargs(code)
return inspect.ArgSpec(args, varargs, varkw, func.__defaults__)
示例4: test_getargspec
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import ArgSpec [as 别名]
def test_getargspec():
empty = inspect.ArgSpec(args=[], varargs=None, keywords=None, defaults=None)
assert_eq(empty, qcore.inspection.getargspec(test_get_subclass_tree))
assert_eq(empty, qcore.inspection.getargspec(qcore.inspection.lazy_stack))
emptymethod = inspect.ArgSpec(
args=["self"], varargs=None, keywords=None, defaults=None
)
assert_eq(emptymethod, qcore.inspection.getargspec(X.myinstancemethod))
assert_eq(emptymethod, qcore.inspection.getargspec(X().myinstancemethod))
emptyclsmethod = inspect.ArgSpec(
args=["cls"], varargs=None, keywords=None, defaults=None
)
assert_eq(emptyclsmethod, qcore.inspection.getargspec(X.myclassmethod))
spec = inspect.ArgSpec(
args=["a", "b", "c", "d"], varargs=None, keywords="f", defaults=("e",)
)
assert_eq(spec, qcore.inspection.getargspec(fun_with_args))
示例5: getargspec
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import ArgSpec [as 别名]
def getargspec(object): # pylint: disable=redefined-builtin
"""TFDecorator-aware replacement for inspect.getargspec.
Args:
object: A callable, possibly decorated.
Returns:
The `ArgSpec` that describes the signature of the outermost decorator that
changes the callable's signature. If the callable is not decorated,
`inspect.getargspec()` will be called directly on the callable.
"""
decorators, target = tf_decorator.unwrap(object)
return next((d.decorator_argspec for d in decorators
if d.decorator_argspec is not None), _inspect.getargspec(target))
示例6: _passed
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import ArgSpec [as 别名]
def _passed(argspec, positional, keyword):
"""
Take an I{inspect.ArgSpec}, a tuple of positional arguments, and a dict of
keyword arguments, and return a mapping of arguments that were actually
passed to their passed values.
@param argspec: The argument specification for the function to inspect.
@type argspec: I{inspect.ArgSpec}
@param positional: The positional arguments that were passed.
@type positional: L{tuple}
@param keyword: The keyword arguments that were passed.
@type keyword: L{dict}
@return: A dictionary mapping argument names (those declared in C{argspec})
to values that were passed explicitly by the user.
@rtype: L{dict} mapping L{str} to L{object}
"""
result = {}
unpassed = len(argspec.args) - len(positional)
if argspec.keywords is not None:
kwargs = result[argspec.keywords] = {}
if unpassed < 0:
if argspec.varargs is None:
raise TypeError("Too many arguments.")
else:
result[argspec.varargs] = positional[len(argspec.args):]
for name, value in zip(argspec.args, positional):
result[name] = value
for name, value in keyword.items():
if name in argspec.args:
if name in result:
raise TypeError("Already passed.")
result[name] = value
elif argspec.keywords is not None:
kwargs[name] = value
else:
raise TypeError("no such param")
return result
示例7: _getargspec_init
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import ArgSpec [as 别名]
def _getargspec_init(method):
try:
return inspect.getargspec(method)
except TypeError:
if method is object.__init__:
return ArgSpec(["self"], None, None, None)
else:
return ArgSpec(["self"], "args", "kwargs", None)
示例8: add_request_to_signature
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import ArgSpec [as 别名]
def add_request_to_signature(function):
argspec = inspect.getargspec(function)
return inspect.ArgSpec(argspec.args + ['request'], argspec.varargs, argspec.keywords, argspec.defaults)
示例9: _passedArgSpec
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import ArgSpec [as 别名]
def _passedArgSpec(argspec, positional, keyword):
"""
Take an I{inspect.ArgSpec}, a tuple of positional arguments, and a dict of
keyword arguments, and return a mapping of arguments that were actually
passed to their passed values.
@param argspec: The argument specification for the function to inspect.
@type argspec: I{inspect.ArgSpec}
@param positional: The positional arguments that were passed.
@type positional: L{tuple}
@param keyword: The keyword arguments that were passed.
@type keyword: L{dict}
@return: A dictionary mapping argument names (those declared in C{argspec})
to values that were passed explicitly by the user.
@rtype: L{dict} mapping L{str} to L{object}
"""
result = {}
unpassed = len(argspec.args) - len(positional)
if argspec.keywords is not None:
kwargs = result[argspec.keywords] = {}
if unpassed < 0:
if argspec.varargs is None:
raise TypeError("Too many arguments.")
else:
result[argspec.varargs] = positional[len(argspec.args):]
for name, value in zip(argspec.args, positional):
result[name] = value
for name, value in keyword.items():
if name in argspec.args:
if name in result:
raise TypeError("Already passed.")
result[name] = value
elif argspec.keywords is not None:
kwargs[name] = value
else:
raise TypeError("no such param")
return result
示例10: get_default_args
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import ArgSpec [as 别名]
def get_default_args(o):
"""获取函数的默认参数名-值映射
"""
argspec = o
if not isinstance(o, inspect.ArgSpec):
argspec = inspect.getargspec(o)
if not argspec.defaults:
return {}
return dict(zip(argspec.args[-len(argspec.defaults):],
argspec.defaults))
# 线性集合类型
示例11: set_preprocess_fn
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import ArgSpec [as 别名]
def set_preprocess_fn(self, preprocess_fn): # pytype: disable=invalid-annotation
"""Register the preprocess_fn used during the input data generation.
Note, the preprocess_fn can only have `features` and optionally `labels` as
inputs. The `mode` has to be abstracted by using a closure or
functools.partial prior to passing a preprocessor.preprocess function.
For example using functools:
set_preprocess_fn(
functools.partial(preprocessor.preprocess,
mode=tf.estimator.ModeKeys.TRAIN))
Args:
preprocess_fn: The function called during the input dataset generation to
preprocess the data.
"""
if isinstance(preprocess_fn, functools.partial): # pytype: disable=wrong-arg-types
# Note, we do not combine both conditions into one since
# inspect.getargspec does not work for functools.partial objects.
if 'mode' not in preprocess_fn.keywords:
raise ValueError('The preprocess_fn mode has to be set if a partial'
'function has been passed.')
else:
if six.PY3:
argspec = inspect.getfullargspec(preprocess_fn)
# first 4 element of fullspec corresponds to spec:
# https://docs.python.org/3.4/library/inspect.html
argspec = inspect.ArgSpec(*argspec[:4])
else:
argspec = inspect.getargspec(preprocess_fn) # pylint: disable=deprecated-method
if 'mode' in argspec.args:
raise ValueError('The passed preprocess_fn has an open argument `mode`'
'which should be patched by a closure or with '
'functools.partial.')
self._preprocess_fn = preprocess_fn
示例12: argspec
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import ArgSpec [as 别名]
def argspec(callable_obj):
"""
Returns an ArgSpec object for functions, staticmethods, instance
methods, classmethods and partials.
Note that the args list for instance and class methods are those as
seen by the user. In other words, the first argument which is
conventionally called 'self' or 'cls' is omitted in these cases.
"""
if (isinstance(callable_obj, type)
and issubclass(callable_obj, param.ParameterizedFunction)):
# Parameterized function.__call__ considered function in py3 but not py2
spec = _getargspec(callable_obj.__call__)
args = spec.args[1:]
elif inspect.isfunction(callable_obj): # functions and staticmethods
spec = _getargspec(callable_obj)
args = spec.args
elif isinstance(callable_obj, partial): # partials
arglen = len(callable_obj.args)
spec = _getargspec(callable_obj.func)
args = [arg for arg in spec.args[arglen:] if arg not in callable_obj.keywords]
elif inspect.ismethod(callable_obj): # instance and class methods
spec = _getargspec(callable_obj)
args = spec.args[1:]
else: # callable objects
return argspec(callable_obj.__call__)
return inspect.ArgSpec(args=args,
varargs=spec.varargs,
keywords=get_keywords(spec),
defaults=spec.defaults)
示例13: noargs
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import ArgSpec [as 别名]
def noargs(self):
"Returns True if the callable takes no arguments"
noargs = inspect.ArgSpec(args=[], varargs=None, keywords=None, defaults=None)
return self.argspec == noargs
示例14: argspec
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import ArgSpec [as 别名]
def argspec(self):
return inspect.ArgSpec(args=[], varargs=None, keywords=None, defaults=None)
示例15: zip_arguments_defaults
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import ArgSpec [as 别名]
def zip_arguments_defaults(argspec):
# type: (inspect.ArgSpec) -> Iterable
if not argspec.defaults:
return []
return zip(
argspec.args[-len(argspec.defaults):],
argspec.defaults)