本文整理汇总了Python中inspect.signature方法的典型用法代码示例。如果您正苦于以下问题:Python inspect.signature方法的具体用法?Python inspect.signature怎么用?Python inspect.signature使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类inspect
的用法示例。
在下文中一共展示了inspect.signature方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import signature [as 别名]
def __init__(self, constraint: Callable[..., bool]) -> None:
"""
Args:
constraint:
The constraint callback.
Raises:
ValueError:
If the callback has positional-only or variable parameters (\*args and \*\*kwargs).
"""
self.constraint = constraint
signature = inspect.signature(constraint)
self._variables = OrderedDict()
for param in signature.parameters.values():
if param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD or param.kind == inspect.Parameter.KEYWORD_ONLY:
self._variables[param.name] = param.name
elif param.kind == inspect.Parameter.VAR_KEYWORD:
raise ValueError("Constraint cannot have variable keyword arguments ({})".format(param.name))
else:
raise ValueError(
"Constraint cannot have positional-only or variable positional arguments ({})".format(param.name)
)
示例2: map_arg
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import signature [as 别名]
def map_arg(**maps):
"""
Apply a mapping on certain argument before calling the original function.
Args:
maps (dict): {argument_name: map_func}
"""
def deco(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
# getcallargs was deprecated since 3.5
sig = inspect.signature(func)
argmap = sig.bind_partial(*args, **kwargs).arguments
for k, map_func in maps.items():
if k in argmap:
argmap[k] = map_func(argmap[k])
return func(**argmap)
return wrapper
return deco
示例3: get_call_args
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import signature [as 别名]
def get_call_args(f, *args, **kwargs):
sig = signature(f)
arguments = sig.bind(*args, **kwargs).arguments
# apply defaults:
new_arguments = []
for name, param in sig.parameters.items():
try:
new_arguments.append((name, arguments[name]))
except KeyError:
if param.default is not param.empty:
val = param.default
elif param.kind is param.VAR_POSITIONAL:
val = ()
elif param.kind is param.VAR_KEYWORD:
val = {}
else:
continue
new_arguments.append((name, val))
return collections.OrderedDict(new_arguments)
示例4: _fill
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import signature [as 别名]
def _fill():
for name in dir(types):
update = getattr(types, name)
if getattr(update, 'SUBCLASS_OF_ID', None) == 0x9f89304e:
cid = update.CONSTRUCTOR_ID
sig = inspect.signature(update.__init__)
for param in sig.parameters.values():
vec = _has_field.get((param.name, param.annotation))
if vec is not None:
vec.append(cid)
# Future-proof check: if the documentation format ever changes
# then we won't be able to pick the update types we are interested
# in, so we must make sure we have at least an update for each field
# which likely means we are doing it right.
if not all(_has_field.values()):
raise RuntimeError('FIXME: Did the init signature or updates change?')
# We use a function to avoid cluttering the globals (with name/update/cid/doc)
示例5: _check_func
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import signature [as 别名]
def _check_func(self):
"""Make sure the function parameters don't violate any rules."""
signature = inspect.signature(self.handler)
if 'self' in signature.parameters:
if self._instance is None:
raise TypeError("{} is a class method, but instance was not "
"given!".format(self.name))
arg_info = self.get_arg_info(signature.parameters['self'])
if arg_info.value is not None:
raise TypeError("{}: Can't fill 'self' with value!"
.format(self.name))
elif 'self' not in signature.parameters and self._instance is not None:
raise TypeError("{} is not a class method, but instance was "
"given!".format(self.name))
elif any(param.kind == inspect.Parameter.VAR_KEYWORD
for param in signature.parameters.values()):
raise TypeError("{}: functions with varkw arguments are not "
"supported!".format(self.name))
示例6: __call__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import signature [as 别名]
def __call__(self, func: typing.Callable) -> typing.Callable:
funcname = func.__name__
if self._argname not in inspect.signature(func).parameters:
raise ValueError("{} has no argument {}!".format(funcname,
self._argname))
if not hasattr(func, 'qute_args'):
func.qute_args = {} # type: ignore[attr-defined]
elif func.qute_args is None: # type: ignore[attr-defined]
raise ValueError("@cmdutils.argument got called above (after) "
"@cmdutils.register for {}!".format(funcname))
arginfo = command.ArgInfo(**self._kwargs)
func.qute_args[self._argname] = arginfo # type: ignore[attr-defined]
return func
示例7: signature
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import signature [as 别名]
def signature(f):
sig = inspect.signature(f)
args = [
p.name for p in sig.parameters.values()
if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
]
varargs = [
p.name for p in sig.parameters.values()
if p.kind == inspect.Parameter.VAR_POSITIONAL
]
varargs = varargs[0] if varargs else None
keywords = [
p.name for p in sig.parameters.values()
if p.kind == inspect.Parameter.VAR_KEYWORD
]
keywords = keywords[0] if keywords else None
defaults = [
p.default for p in sig.parameters.values()
if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
and p.default is not p.empty
] or None
argspec = namedtuple('Signature', ['args', 'defaults',
'varargs', 'keywords'])
return argspec(args, defaults, varargs, keywords)
示例8: test_set_axis_prior_to_deprecation_signature
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import signature [as 别名]
def test_set_axis_prior_to_deprecation_signature(self):
df = DataFrame({'A': [1.1, 2.2, 3.3],
'B': [5.0, 6.1, 7.2],
'C': [4.4, 5.5, 6.6]},
index=[2010, 2011, 2012])
expected = {0: df.copy(),
1: df.copy()}
expected[0].index = list('abc')
expected[1].columns = list('abc')
expected['index'] = expected[0]
expected['columns'] = expected[1]
# old signature
for axis in expected:
with tm.assert_produces_warning(FutureWarning):
result = df.set_axis(axis, list('abc'), inplace=False)
tm.assert_frame_equal(result, expected[axis])
示例9: _validate_hook
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import signature [as 别名]
def _validate_hook(self, name: str, hook: Callable) -> None:
"""Basic validation for hooks being registered."""
spec = self._specs.get(name)
if spec is None:
raise TypeError(f"There is no hook with name '{name}'")
# Some hooks are not present on all levels. We need to avoid registering hooks on wrong levels
if self.scope not in spec.scopes:
scopes = ", ".join(scope.name for scope in spec.scopes)
raise ValueError(
f"Can not register hook '{name}' on {self.scope.name} scope dispatcher. "
f"Use a dispatcher with {scopes} scope(s) instead"
)
signature = inspect.signature(hook)
if len(signature.parameters) != len(spec.signature.parameters):
raise TypeError(
f"Hook '{name}' takes {len(spec.signature.parameters)} arguments but {len(signature.parameters)} is defined"
)
示例10: ensure_interface
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import signature [as 别名]
def ensure_interface(function):
signature = inspect.signature(function)
parameters = signature.parameters
@wraps(function)
def wrapped(*args, **kwargs):
bound = signature.bind(*args, **kwargs)
for name, value in bound.arguments.items():
annotation = parameters[name].annotation
if not isinstance(annotation, ABCMeta):
continue
if not isinstance(value, annotation):
raise TypeError(
"{} does not implement {} interface"
"".format(value, annotation)
)
function(*args, **kwargs)
return wrapped
开发者ID:PacktPublishing,项目名称:Expert-Python-Programming_Second-Edition,代码行数:25,代码来源:interfaces_annotations.py
示例11: _check_signature
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import signature [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))
示例12: test_field_named_self
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import signature [as 别名]
def test_field_named_self(self):
@dataclass
class C:
self: str
c=C('foo')
self.assertEqual(c.self, 'foo')
# Make sure the first parameter is not named 'self'.
sig = inspect.signature(C.__init__)
first = next(iter(sig.parameters))
self.assertNotEqual('self', first)
# But we do use 'self' if no field named self.
@dataclass
class C:
selfx: str
# Make sure the first parameter is named 'self'.
sig = inspect.signature(C.__init__)
first = next(iter(sig.parameters))
self.assertEqual('self', first)
示例13: create_config
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import signature [as 别名]
def create_config(klass, config, msg):
try:
return klass(**config)
except TypeError:
# Inspect the GlobalConfig constructor to find which
# parameters are required and don't have a default
# value.
required_args = {
name
for name, param in inspect.signature(klass.__init__).parameters.items()
if param.default == inspect._empty
and name not in {'self', 'kwargs'}
}
missing_args = required_args - config.keys()
missing = ', '.join(
"'{arg}'".format(arg=arg)
for arg in sorted(missing_args)
)
raise BriefcaseConfigError(
"{msg} is incomplete (missing {missing})".format(
msg=msg,
missing=missing
)
)
示例14: __call__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import signature [as 别名]
def __call__(self, image, labels, return_inverter=False):
self.expand.labels_format = self.labels_format
self.random_crop.labels_format = self.labels_format
self.random_flip.labels_format = self.labels_format
self.resize.labels_format = self.labels_format
inverters = []
for transform in self.sequence:
if return_inverter and ('return_inverter' in inspect.signature(transform).parameters):
image, labels, inverter = transform(image, labels, return_inverter=True)
inverters.append(inverter)
else:
image, labels = transform(image, labels)
if return_inverter:
return image, labels, inverters[::-1]
else:
return image, labels
开发者ID:pierluigiferrari,项目名称:data_generator_object_detection_2d,代码行数:21,代码来源:data_augmentation_chain_original_ssd.py
示例15: callback
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import signature [as 别名]
def callback(self, function):
self._callback = function
self.module = function.__module__
signature = inspect.signature(function)
self.params = signature.parameters.copy()
# PEP-563 allows postponing evaluation of annotations with a __future__
# import. When postponed, Parameter.annotation will be a string and must
# be replaced with the real value for the converters to work later on
for key, value in self.params.items():
if isinstance(value.annotation, str):
self.params[key] = value = value.replace(annotation=eval(value.annotation, function.__globals__))
# fail early for when someone passes an unparameterized Greedy type
if value.annotation is converters.Greedy:
raise TypeError('Unparameterized Greedy[...] is disallowed in signature.')