本文整理汇总了Python中inspect.Signature方法的典型用法代码示例。如果您正苦于以下问题:Python inspect.Signature方法的具体用法?Python inspect.Signature怎么用?Python inspect.Signature使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类inspect
的用法示例。
在下文中一共展示了inspect.Signature方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _call_with_selection
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import Signature [as 别名]
def _call_with_selection(func):
"""Decorator that passes a `Selection` built from the non-kwonly args."""
wrapped_kwonly_params = [
param for param in inspect.signature(func).parameters.values()
if param.kind == param.KEYWORD_ONLY]
sel_sig = inspect.signature(Selection)
default_sel_sig = sel_sig.replace(
parameters=[param.replace(default=None) if param.default is param.empty
else param
for param in sel_sig.parameters.values()])
@functools.wraps(func)
def wrapper(*args, **kwargs):
extra_kw = {param.name: kwargs.pop(param.name)
for param in wrapped_kwonly_params if param.name in kwargs}
ba = default_sel_sig.bind(*args, **kwargs)
ba.apply_defaults()
sel = Selection(*ba.args, **ba.kwargs)
return func(sel, **extra_kw)
wrapper.__signature__ = Signature(
[*sel_sig.parameters.values(), *wrapped_kwonly_params])
return wrapper
示例2: adapt_args
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import Signature [as 别名]
def adapt_args(args: list, kwargs: dict, spec: inspect.Signature,
deserializers=DESERIALIZERS) -> Tuple[list, dict]:
"""Takes the arguments to a function (as an arg list and a dict of keyword
args) and adapts them according to the spec.
"""
parameters = spec.parameters
adapted_args = [
adapt_arg(arg, parameters[arg_name].annotation, deserializers)
for arg, arg_name in zip(args, parameters)
]
adapted_kwargs = {
arg_name: adapt_arg(kwargs[arg_name], parameters[arg_name].annotation, deserializers)
for arg_name in kwargs
}
return adapted_args, adapted_kwargs
示例3: get_signature
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import Signature [as 别名]
def get_signature(
fn: Union[types.FunctionType, types.MethodType]) -> inspect.Signature:
"""Returns the `inspect.Signature` structure for the given function or method.
Args:
fn: The Python function or Tensorflow function to analyze.
Returns:
An `inspect.Signature`.
Raises:
TypeError: if the argument is not of a supported type.
"""
if isinstance(fn, (types.FunctionType, types.MethodType)):
return inspect.signature(fn)
elif function.is_tf_function(fn):
return inspect.signature(fn.python_function)
else:
raise TypeError('Expected a Python function or a defun, found {}.'.format(
py_typecheck.type_string(type(fn))))
示例4: test_signature_hashable
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import Signature [as 别名]
def test_signature_hashable(self):
S = inspect.Signature
P = inspect.Parameter
def foo(a): pass
foo_sig = inspect.signature(foo)
manual_sig = S(parameters=[P('a', P.POSITIONAL_OR_KEYWORD)])
self.assertEqual(hash(foo_sig), hash(manual_sig))
self.assertNotEqual(hash(foo_sig),
hash(manual_sig.replace(return_annotation='spam')))
def bar(a) -> 1: pass
self.assertNotEqual(hash(foo_sig), hash(inspect.signature(bar)))
def foo(a={}): pass
with self.assertRaisesRegex(TypeError, 'unhashable type'):
hash(inspect.signature(foo))
def foo(a) -> {}: pass
with self.assertRaisesRegex(TypeError, 'unhashable type'):
hash(inspect.signature(foo))
示例5: create_signature
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import Signature [as 别名]
def create_signature(args, optional_args):
""" Dynamically create a signature for a function from strings.
This function can be used to create a signature for a dynamically
generated function without generating a string representation of
the function code and making an explicit eval call.
Parameters
----------
args : list
List of strings that name the required arguments of a function.
optional_args : list
List of strings that name the optional arguments of a function.
Returns
-------
Signature(p) : inspect.Signature instance
A Signature object that can be used to validate arguments in
a dynamically created function.
"""
p = [Parameter(x, Parameter.POSITIONAL_OR_KEYWORD) for x in args]
p += [Parameter(x, Parameter.KEYWORD_ONLY, default='DEFAULT')
for x in optional_args]
return Signature(p)
示例6: __new__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import Signature [as 别名]
def __new__(cls, f: Callable[..., T]):
f.__model__ = cls.__model__
self = super().__new__(cls, f)
self.__callable = True
self.__compiled_model = None
for prop in cls.__model__.attribute_map.keys():
setattr(self, prop, None)
# __props__ is set by Type[Prop] decorator
for prop in getattr(f, "__props__", {}):
if prop not in self.__model__.attribute_map:
raise ValueError(f"Unknown property '{prop}' of '{self.__model__}")
setattr(self, prop, f.__props__[prop])
sig: inspect.Signature = inspect.signature(f)
sig = sig.replace(return_annotation=cls.__model__)
setattr(self, "__signature__", sig)
return self
示例7: _merge_args_and_kwargs
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import Signature [as 别名]
def _merge_args_and_kwargs(signature: inspect.Signature, name: str,
args: Any, kwargs: Any) -> Dict[str, Any]:
"""Returns one kwargs dictionary or
raises an exeption in case of overlapping-name problems."""
param_names = [param.name for param in signature.parameters.values()]
if len(args) > len(param_names):
raise TypeError(f'Too many parameters for {name}.')
args_as_kwargs = dict(zip(param_names, list(args)))
keys_in_args_and_kwargs = set.intersection(set(args_as_kwargs.keys()),
set(kwargs.keys()))
if keys_in_args_and_kwargs:
raise TypeError(f'The following parameters are given as '
f'arg and kwarg in call of {name}: '
f'{keys_in_args_and_kwargs}')
return {**args_as_kwargs, **kwargs}
示例8: log_success
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import Signature [as 别名]
def log_success(
self, class_name: str, name: str, duration: float, signature: Optional[Signature] = None
) -> None:
"""
Log the function or property call is successfully finished.
:param class_name: the target class name
:param name: the target function or property name
:param duration: the duration to finish the function or property call
:param signature: the signature if the target is a function, else None
"""
if self.logger.isEnabledFor(logging.INFO):
msg = (
"A {function} `{class_name}.{name}{signature}` was successfully finished "
"after {duration:.3f} ms."
).format(
class_name=class_name,
name=name,
signature=_format_signature(signature),
duration=duration * 1000,
function="function" if signature is not None else "property",
)
self.logger.info(msg)
示例9: log_missing
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import Signature [as 别名]
def log_missing(
self,
class_name: str,
name: str,
is_deprecated: bool = False,
signature: Optional[Signature] = None,
) -> None:
"""
Log the missing or deprecated function or property is called.
:param class_name: the target class name
:param name: the target function or property name
:param is_deprecated: True if the function or property is marked as deprecated
:param signature: the original function signature if the target is a function, else None
"""
if self.logger.isEnabledFor(logging.INFO):
msg = "A {deprecated} {function} `{class_name}.{name}{signature}` was called.".format(
class_name=class_name,
name=name,
signature=_format_signature(signature),
function="function" if signature is not None else "property",
deprecated="deprecated" if is_deprecated else "missing",
)
self.logger.info(msg)
示例10: _get_function_metadata
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import Signature [as 别名]
def _get_function_metadata(
cls, input_function: Callable
) -> Dict[str, Any]:
"""
Metadata about arguments documentation and the function itself
"""
signature: inspect.Signature = inspect.signature(input_function)
arguments_metadata: Dict[str, Dict[str, Any]] = {}
for key, parameter in signature.parameters.items():
arg_type, arg_choices, arg_defaults = cls.get_param_info(parameter)
arguments_metadata[key] = {
"default": arg_defaults,
"type": arg_type,
"choices": arg_choices,
}
metadata = {
"args": arguments_metadata,
"doc": inspect.getdoc(input_function),
"name": input_function.__name__,
}
return metadata
示例11: __call__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import Signature [as 别名]
def __call__(self, *args, **kwargs):
"""
Evaluate the model for a certain value of the independent vars and parameters.
Signature for this function contains independent vars and parameters, NOT dependent and sigma vars.
Can be called with both ordered and named parameters. Order is independent vars first, then parameters.
Alphabetical order within each group.
:param args: Ordered arguments for the parameters and independent
variables
:param kwargs: Keyword arguments for the parameters and independent
variables
:return: A namedtuple of all the dependent vars evaluated at the desired point. Will always return a tuple,
even for scalar valued functions. This is done for consistency.
"""
return ModelOutput(self.keys(), self.eval_components(*args, **kwargs))
示例12: __new__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import Signature [as 别名]
def __new__(mcs, name, bases, dct):
fields = []
for k, v in dct.items():
if isinstance(v, Field):
fields.append(v)
dct['_fields'] = fields
if '__init__' not in dct:
from inspect import Signature
def __init__(self, **kwargs):
super(cls, self).__init__(**kwargs)
__init__.__signature__ = Signature(parameters=[field.to_parameter() for field in fields])
dct['__init__'] = __init__
try:
if TypedStruct in bases and '__doc__' not in dct:
# If we don't do this, IPython will display the TypedStruct docstring
dct['__doc__'] = ""
except NameError: # TypedStruct itself is defined here
pass
cls = super().__new__(mcs, name, bases, dct)
return cls
示例13: rewrite_axis_style_signature
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import Signature [as 别名]
def rewrite_axis_style_signature(name, extra_params):
def decorate(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
if not PY2:
kind = inspect.Parameter.POSITIONAL_OR_KEYWORD
params = [
inspect.Parameter('self', kind),
inspect.Parameter(name, kind, default=None),
inspect.Parameter('index', kind, default=None),
inspect.Parameter('columns', kind, default=None),
inspect.Parameter('axis', kind, default=None),
]
for pname, default in extra_params:
params.append(inspect.Parameter(pname, kind, default=default))
sig = inspect.Signature(params)
func.__signature__ = sig
return wrapper
return decorate
# Substitution and Appender are derived from matplotlib.docstring (1.1.0)
# module http://matplotlib.org/users/license.html
示例14: get_typed_signature
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import Signature [as 别名]
def get_typed_signature(call: Callable) -> inspect.Signature:
signature = inspect.signature(call)
globalns = getattr(call, "__globals__", {})
typed_params = [
inspect.Parameter(
name=param.name,
kind=param.kind,
default=param.default,
annotation=get_typed_annotation(param, globalns),
)
for param in signature.parameters.values()
]
typed_signature = inspect.Signature(typed_params)
return typed_signature
示例15: add_method
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import Signature [as 别名]
def add_method(self, method_name: str, method_fn, rpc_signature: RPCSignature,
method_signature: inspect.Signature = None):
if method_signature is None:
method_signature = inspect.signature(method_fn)
if len(method_signature.parameters) == 1:
def method_fn_with_headers(arg, request):
return method_fn(arg)
elif len(method_signature.parameters) == 2:
if list(method_signature.parameters.values())[1].name == "request":
method_fn_with_headers = method_fn
else:
raise ValueError("Expected second parameter 'request'")
else:
raise ValueError("Expected method_fn to have exactly one or two parameters")
self.methods[method_name] = BoundRPCMethod(method_fn_with_headers, rpc_signature)