本文整理匯總了Python中inspect.Parameter方法的典型用法代碼示例。如果您正苦於以下問題:Python inspect.Parameter方法的具體用法?Python inspect.Parameter怎麽用?Python inspect.Parameter使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類inspect
的用法示例。
在下文中一共展示了inspect.Parameter方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_type_conv_invalid
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import Parameter [as 別名]
def test_type_conv_invalid(typ, value, multi):
param = inspect.Parameter('foo', inspect.Parameter.POSITIONAL_ONLY)
if multi:
msg = 'foo: Invalid value {}'.format(value)
elif typ is Enum:
msg = ('foo: Invalid value {} - expected one of: foo, '
'foo-bar'.format(value))
else:
msg = 'foo: Invalid {} value {}'.format(typ.__name__, value)
with pytest.raises(cmdexc.ArgumentTypeError, match=msg):
if multi:
argparser.multitype_conv(param, [typ], value)
else:
argparser.type_conv(param, typ, value)
示例2: _check_func
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import Parameter [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))
示例3: _inspect_special_param
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import Parameter [as 別名]
def _inspect_special_param(self, param):
"""Check if the given parameter is a special one.
Args:
param: The inspect.Parameter to handle.
Return:
True if the parameter is special, False otherwise.
"""
arg_info = self.get_arg_info(param)
if arg_info.value is None:
return False
elif arg_info.value == usertypes.CommandValue.count:
if param.default is inspect.Parameter.empty:
raise TypeError("{}: handler has count parameter "
"without default!".format(self.name))
return True
elif isinstance(arg_info.value, usertypes.CommandValue):
return True
else:
raise TypeError("{}: Invalid value={!r} for argument '{}'!"
.format(self.name, arg_info.value, param.name))
raise utils.Unreachable
示例4: _get_type
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import Parameter [as 別名]
def _get_type(self, param):
"""Get the type of an argument from its default value or annotation.
Args:
param: The inspect.Parameter to look at.
"""
arg_info = self.get_arg_info(param)
if arg_info.value:
# Filled values are passed 1:1
return None
elif param.kind in [inspect.Parameter.VAR_POSITIONAL,
inspect.Parameter.VAR_KEYWORD]:
# For *args/**kwargs we only support strings
assert param.annotation in [inspect.Parameter.empty, str], param
return None
elif param.annotation is not inspect.Parameter.empty:
return param.annotation
elif param.default not in [None, inspect.Parameter.empty]:
return type(param.default)
else:
return str
示例5: _add_special_arg
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import Parameter [as 別名]
def _add_special_arg(self, *, value, param, args, kwargs):
"""Add a special argument value to a function call.
Arguments:
value: The value to add.
param: The parameter being filled.
args: The positional argument list. Gets modified directly.
kwargs: The keyword argument dict. Gets modified directly.
"""
if param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD:
args.append(value)
elif param.kind == inspect.Parameter.KEYWORD_ONLY:
kwargs[param.name] = value
else:
raise TypeError("{}: invalid parameter type {} for argument "
"{!r}!".format(self.name, param.kind, param.name))
示例6: callback
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import Parameter [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.')
示例7: clean_params
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import Parameter [as 別名]
def clean_params(self):
"""OrderedDict[:class:`str`, :class:`inspect.Parameter`]:
Retrieves the parameter OrderedDict without the context or self parameters.
Useful for inspecting signature.
"""
result = self.params.copy()
if self.cog is not None:
# first parameter is self
result.popitem(last=False)
try:
# first/second parameter is context
result.popitem(last=False)
except Exception:
raise ValueError('Missing context parameter') from None
return result
示例8: _IsDefinableParameter
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import Parameter [as 別名]
def _IsDefinableParameter(parameter):
"""Checks if the parameter can be defined in `Params`.
Args:
parameter: inspect.Parameter to be checked.
Returns:
True if the `parameter`'s kind is either `POSITIONAL_OR_KEYWORD` or
`KEYWORD_ONLY` which are definable in `Params`, False if it is either
`VAR_POSITIONAL` or `VAR_KEYWORD` which are ignorable.
Raises:
ValueError: The `parameter` has another kind which are possibly not
supported, e.g., `POSITIONAL_ONLY` parameters.
"""
if parameter.kind in DEFINABLE_PARAMETER_KINDS:
return True
elif parameter.kind in IGNORABLE_PARAMETER_KINDS:
return False
else:
raise ValueError('Unsupported parameter signature `%s` with kind `%s`.' %
(parameter.name, parameter.kind))
示例9: _ExtractParameters
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import Parameter [as 別名]
def _ExtractParameters(func, ignore, bound):
"""Extracts parameters of func which can be defined in Params.
Args:
func: A callable to be analysed.
ignore: A collection of parameter names in `func` to be ignored.
bound: Whether the `func` is used as a bound function (an object method or a
class method) or not. If True, the first parameter of the `func` will be
ignored.
Returns:
A generator of `inspect.Parameter` representing definable parameters.
"""
ignore = set(ignore if ignore is not None else ())
# Obtains parameter signatures.
parameters = tuple(inspect.signature(func).parameters.values())
# Ignores the bound parameter: typically `self` or `cls`.
parameters = parameters[(1 if bound else 0):]
# Filters unnecessary parameters.
parameters = filter(_IsDefinableParameter, parameters)
parameters = (p for p in parameters if p.name not in ignore)
return parameters
示例10: add_non_field_param_to_dependency
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import Parameter [as 別名]
def add_non_field_param_to_dependency(
*, param: inspect.Parameter, dependant: Dependant
) -> Optional[bool]:
if lenient_issubclass(param.annotation, Request):
dependant.request_param_name = param.name
return True
elif lenient_issubclass(param.annotation, WebSocket):
dependant.websocket_param_name = param.name
return True
elif lenient_issubclass(param.annotation, Response):
dependant.response_param_name = param.name
return True
elif lenient_issubclass(param.annotation, BackgroundTasks):
dependant.background_tasks_param_name = param.name
return True
elif lenient_issubclass(param.annotation, SecurityScopes):
dependant.security_scopes_param_name = param.name
return True
return None
示例11: getdoc
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import Parameter [as 別名]
def getdoc(c_or_f: Union[Callable, type]) -> Optional[str]:
if getattr(c_or_f, '__doc__', None) is None:
return None
doc = inspect.getdoc(c_or_f)
if isinstance(c_or_f, type) and hasattr(c_or_f, '__init__'):
sig = inspect.signature(c_or_f.__init__)
else:
sig = inspect.signature(c_or_f)
def type_doc(name: str):
param: inspect.Parameter = sig.parameters[name]
cls = getattr(param.annotation, '__qualname__', repr(param.annotation))
if param.default is not param.empty:
return f'{cls}, optional (default: {param.default!r})'
else:
return cls
return '\n'.join(
f'{line} : {type_doc(line)}' if line.strip() in sig.parameters else line
for line in doc.split('\n')
)
示例12: test_get_defun_argspec_with_typed_non_eager_defun
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import Parameter [as 別名]
def test_get_defun_argspec_with_typed_non_eager_defun(self):
# In a tf.function with a defined input signature, **kwargs or default
# values are not allowed, but *args are, and the input signature may overlap
# with *args.
fn = tf.function(lambda x, y, *z: None, (
tf.TensorSpec(None, tf.int32),
tf.TensorSpec(None, tf.bool),
tf.TensorSpec(None, tf.float32),
tf.TensorSpec(None, tf.float32),
))
self.assertEqual(
collections.OrderedDict(function_utils.get_signature(fn).parameters),
collections.OrderedDict(
x=inspect.Parameter('x', inspect.Parameter.POSITIONAL_OR_KEYWORD),
y=inspect.Parameter('y', inspect.Parameter.POSITIONAL_OR_KEYWORD),
z=inspect.Parameter('z', inspect.Parameter.VAR_POSITIONAL),
))
示例13: test_get_signature_with_class_instance_method
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import Parameter [as 別名]
def test_get_signature_with_class_instance_method(self):
class C:
def __init__(self, x):
self._x = x
def foo(self, y):
return self._x * y
c = C(5)
signature = function_utils.get_signature(c.foo)
self.assertEqual(
signature.parameters,
collections.OrderedDict(
y=inspect.Parameter('y', inspect.Parameter.POSITIONAL_OR_KEYWORD)))
示例14: takes_kwargs
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import Parameter [as 別名]
def takes_kwargs(obj) -> bool:
"""
Checks whether a provided object takes in any positional arguments.
Similar to takes_arg, we do this for both the __init__ function of
the class or a function / method
Otherwise, we raise an error
"""
if inspect.isclass(obj):
signature = inspect.signature(obj.__init__)
elif inspect.ismethod(obj) or inspect.isfunction(obj):
signature = inspect.signature(obj)
else:
raise ConfigurationError(f"object {obj} is not callable")
return any(
p.kind == inspect.Parameter.VAR_KEYWORD # type: ignore
for p in signature.parameters.values()
)
示例15: test_signature_hashable
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import Parameter [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))