Python inspect.Parameter() Examples
The following are 30
code examples of inspect.Parameter().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
inspect
, or try the search function
.
Example #1
Source File: test_inspect.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
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))
Example #2
Source File: command.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
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
Example #3
Source File: command.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
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))
Example #4
Source File: command.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
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
Example #5
Source File: command.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
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))
Example #6
Source File: test_argparser.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
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)
Example #7
Source File: utils.py From epiScanpy with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 = sig.parameters[name] # type: inspect.Parameter cls = getattr(param.annotation, '__qualname__', repr(param.annotation)) if param.default is not param.empty: return '{}, optional (default: {!r})'.format(cls, param.default) else: return cls return '\n'.join( '{} : {}'.format(line, type_doc(line)) if line.strip() in sig.parameters else line for line in doc.split('\n') )
Example #8
Source File: core.py From discord.py with MIT License | 6 votes |
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.')
Example #9
Source File: core.py From discord.py with MIT License | 6 votes |
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
Example #10
Source File: inspect_utils.py From lingvo with Apache License 2.0 | 6 votes |
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))
Example #11
Source File: inspect_utils.py From lingvo with Apache License 2.0 | 6 votes |
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
Example #12
Source File: test_operations_signatures.py From fastapi with MIT License | 6 votes |
def test_signatures_consistency(): base_sig = inspect.signature(APIRouter.get) for method_name in method_names: router_method = getattr(APIRouter, method_name) app_method = getattr(FastAPI, method_name) router_sig = inspect.signature(router_method) app_sig = inspect.signature(app_method) param: inspect.Parameter for key, param in base_sig.parameters.items(): router_param: inspect.Parameter = router_sig.parameters[key] app_param: inspect.Parameter = app_sig.parameters[key] assert param.annotation == router_param.annotation assert param.annotation == app_param.annotation assert param.default == router_param.default assert param.default == app_param.default
Example #13
Source File: utils.py From fastapi with MIT License | 6 votes |
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
Example #14
Source File: test_deprecate.py From learn_python3_spider with MIT License | 6 votes |
def test_invalidParameterType(self): """ Create a fake signature with an invalid parameter type to test error handling. The valid parameter types are specified in L{inspect.Parameter}. """ class FakeSignature: def __init__(self, parameters): self.parameters = parameters class FakeParameter: def __init__(self, name, kind): self.name = name self.kind = kind def func(a, b): pass func(1, 2) parameters = inspect.signature(func).parameters dummyParameters = parameters.copy() dummyParameters['c'] = FakeParameter("fake", "fake") fakeSig = FakeSignature(dummyParameters) self.assertRaises(TypeError, _passedSignature, fakeSig, (1, 2), {})
Example #15
Source File: _utils.py From scanpy with BSD 3-Clause "New" or "Revised" License | 6 votes |
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') )
Example #16
Source File: function_utils_test.py From federated with Apache License 2.0 | 6 votes |
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), ))
Example #17
Source File: function_utils_test.py From federated with Apache License 2.0 | 6 votes |
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)))
Example #18
Source File: from_params.py From allennlp with Apache License 2.0 | 6 votes |
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() )
Example #19
Source File: test_inspect.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_signature_parameter_equality(self): P = inspect.Parameter p = P('foo', default=42, kind=inspect.Parameter.KEYWORD_ONLY) self.assertTrue(p == p) self.assertFalse(p != p) self.assertFalse(p == 42) self.assertTrue(p != 42) self.assertTrue(p == EqualsToAll()) self.assertFalse(p != EqualsToAll()) self.assertTrue(p == P('foo', default=42, kind=inspect.Parameter.KEYWORD_ONLY)) self.assertFalse(p != P('foo', default=42, kind=inspect.Parameter.KEYWORD_ONLY))
Example #20
Source File: test_inspect.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_signature_parameter_object(self): p = inspect.Parameter('foo', default=10, kind=inspect.Parameter.POSITIONAL_ONLY) self.assertEqual(p.name, 'foo') self.assertEqual(p.default, 10) self.assertIs(p.annotation, p.empty) self.assertEqual(p.kind, inspect.Parameter.POSITIONAL_ONLY) with self.assertRaisesRegex(ValueError, 'invalid value'): inspect.Parameter('foo', default=10, kind='123') with self.assertRaisesRegex(ValueError, 'not a valid parameter name'): inspect.Parameter('1', kind=inspect.Parameter.VAR_KEYWORD) with self.assertRaisesRegex(TypeError, 'name must be a str'): inspect.Parameter(None, kind=inspect.Parameter.VAR_KEYWORD) with self.assertRaisesRegex(ValueError, 'is not a valid parameter name'): inspect.Parameter('$', kind=inspect.Parameter.VAR_KEYWORD) with self.assertRaisesRegex(ValueError, 'cannot have default values'): inspect.Parameter('a', default=42, kind=inspect.Parameter.VAR_KEYWORD) with self.assertRaisesRegex(ValueError, 'cannot have default values'): inspect.Parameter('a', default=42, kind=inspect.Parameter.VAR_POSITIONAL) p = inspect.Parameter('a', default=42, kind=inspect.Parameter.POSITIONAL_OR_KEYWORD) with self.assertRaisesRegex(ValueError, 'cannot have default values'): p.replace(kind=inspect.Parameter.VAR_POSITIONAL) self.assertTrue(repr(p).startswith('<Parameter')) self.assertTrue('"a=42"' in repr(p))
Example #21
Source File: test_inspect.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_signature_str_positional_only(self): P = inspect.Parameter S = inspect.Signature def test(a_po, *, b, **kwargs): return a_po, kwargs sig = inspect.signature(test) new_params = list(sig.parameters.values()) new_params[0] = new_params[0].replace(kind=P.POSITIONAL_ONLY) test.__signature__ = sig.replace(parameters=new_params) self.assertEqual(str(inspect.signature(test)), '(a_po, /, *, b, **kwargs)') self.assertEqual(str(S(parameters=[P('foo', P.POSITIONAL_ONLY)])), '(foo, /)') self.assertEqual(str(S(parameters=[ P('foo', P.POSITIONAL_ONLY), P('bar', P.VAR_KEYWORD)])), '(foo, /, **bar)') self.assertEqual(str(S(parameters=[ P('foo', P.POSITIONAL_ONLY), P('bar', P.VAR_POSITIONAL)])), '(foo, /, *bar)')
Example #22
Source File: core.py From CrossHair with MIT License | 5 votes |
def gen_args(sig: inspect.Signature, statespace: StateSpace) -> inspect.BoundArguments: args = sig.bind_partial() for param in sig.parameters.values(): smt_name = param.name + statespace.uniq() proxy_maker = lambda typ, **kw: proxy_for_type(typ, statespace, smt_name, allow_subtypes=True, **kw) has_annotation = (param.annotation != inspect.Parameter.empty) value: object if param.kind == inspect.Parameter.VAR_POSITIONAL: if has_annotation: varargs_type = List[param.annotation] # type: ignore value = proxy_maker(varargs_type) else: value = proxy_maker(List[Any]) elif param.kind == inspect.Parameter.VAR_KEYWORD: if has_annotation: varargs_type = Dict[str, param.annotation] # type: ignore value = cast(dict, proxy_maker(varargs_type)) # Using ** on a dict requires concrete string keys. Force # instiantiation of keys here: value = {k.__str__(): v for (k, v) in value.items()} else: value = proxy_maker(Dict[str, Any]) else: is_self = param.name == 'self' # Object parameters should meet thier invariants iff they are not the # class under test ("self"). meet_class_invariants = not is_self allow_subtypes = not is_self if has_annotation: value = proxy_for_type(param.annotation, statespace, smt_name, meet_class_invariants, allow_subtypes) else: value = proxy_for_type(cast(type, Any), statespace, smt_name, meet_class_invariants, allow_subtypes) debug('created proxy for', param.name, 'as type:', type(value)) args.arguments[param.name] = value return args
Example #23
Source File: test_inspect.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_signature_parameter_hashable(self): P = inspect.Parameter foo = P('foo', kind=P.POSITIONAL_ONLY) self.assertEqual(hash(foo), hash(P('foo', kind=P.POSITIONAL_ONLY))) self.assertNotEqual(hash(foo), hash(P('foo', kind=P.POSITIONAL_ONLY, default=42))) self.assertNotEqual(hash(foo), hash(foo.replace(kind=P.VAR_POSITIONAL)))
Example #24
Source File: test_argparser.py From qutebrowser with GNU General Public License v3.0 | 5 votes |
def test_type_conv_valid(types, value, expected, multi): param = inspect.Parameter('foo', inspect.Parameter.POSITIONAL_ONLY) if multi: assert argparser.multitype_conv(param, types, value) == expected elif len(types) == 1: assert argparser.type_conv(param, types[0], value) == expected
Example #25
Source File: defopt.py From defopt with MIT License | 5 votes |
def signature(func: Callable): """ Return an enhanced signature for ``func``. This function behaves similarly to `inspect.signature`, with the following differences: - Private parameters (starting with an underscore) are not listed. - Parameter annotations are also read from ``func``'s docstring (if a parameter's type is specified both in the signature and the docstring, both types must match). - The docstring for each parameter is available as the `~inspect.Parameter`'s ``.doc`` attribute (in fact, a subclass of `~inspect.Parameter` is used). """ full_sig = inspect.signature(func) doc = _parse_docstring(inspect.getdoc(func)) parameters = [] for param in full_sig.parameters.values(): if param.name.startswith('_'): if param.default is param.empty: raise ValueError( 'Parameter {} of {}{} is private but has no default' .format(param.name, func.__name__, full_sig)) else: parameters.append(Parameter( name=param.name, kind=param.kind, default=param.default, annotation=_get_type(func, param.name), doc=doc.params.get(param.name, _Param(None, None)).text)) return full_sig.replace(parameters=parameters)
Example #26
Source File: test_inspect.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_signature_parameter_replace(self): p = inspect.Parameter('foo', default=42, kind=inspect.Parameter.KEYWORD_ONLY) self.assertIsNot(p, p.replace()) self.assertEqual(p, p.replace()) p2 = p.replace(annotation=1) self.assertEqual(p2.annotation, 1) p2 = p2.replace(annotation=p2.empty) self.assertEqual(p, p2) p2 = p2.replace(name='bar') self.assertEqual(p2.name, 'bar') self.assertNotEqual(p2, p) with self.assertRaisesRegex(ValueError, 'name is a required attribute'): p2 = p2.replace(name=p2.empty) p2 = p2.replace(name='foo', default=None) self.assertIs(p2.default, None) self.assertNotEqual(p2, p) p2 = p2.replace(name='foo', default=p2.empty) self.assertIs(p2.default, p2.empty) p2 = p2.replace(default=42, kind=p2.POSITIONAL_OR_KEYWORD) self.assertEqual(p2.kind, p2.POSITIONAL_OR_KEYWORD) self.assertNotEqual(p2, p) with self.assertRaisesRegex(ValueError, 'invalid value for'): p2 = p2.replace(kind=p2.empty) p2 = p2.replace(kind=p2.KEYWORD_ONLY) self.assertEqual(p2, p)
Example #27
Source File: test_inspect.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_signature_parameter_positional_only(self): with self.assertRaisesRegex(TypeError, 'name must be a str'): inspect.Parameter(None, kind=inspect.Parameter.POSITIONAL_ONLY)
Example #28
Source File: test_inspect.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_signature_bind_positional_only(self): P = inspect.Parameter def test(a_po, b_po, c_po=3, foo=42, *, bar=50, **kwargs): return a_po, b_po, c_po, foo, bar, kwargs sig = inspect.signature(test) new_params = collections.OrderedDict(tuple(sig.parameters.items())) for name in ('a_po', 'b_po', 'c_po'): new_params[name] = new_params[name].replace(kind=P.POSITIONAL_ONLY) new_sig = sig.replace(parameters=new_params.values()) test.__signature__ = new_sig self.assertEqual(self.call(test, 1, 2, 4, 5, bar=6), (1, 2, 4, 5, 6, {})) self.assertEqual(self.call(test, 1, 2), (1, 2, 3, 42, 50, {})) self.assertEqual(self.call(test, 1, 2, foo=4, bar=5), (1, 2, 3, 4, 5, {})) with self.assertRaisesRegex(TypeError, "but was passed as a keyword"): self.call(test, 1, 2, foo=4, bar=5, c_po=10) with self.assertRaisesRegex(TypeError, "parameter is positional only"): self.call(test, 1, 2, c_po=4) with self.assertRaisesRegex(TypeError, "parameter is positional only"): self.call(test, a_po=1, b_po=2)
Example #29
Source File: base.py From dffml with MIT License | 5 votes |
def type_for(cls, param: inspect.Parameter): """ Guess the type based off the default value of the parameter, for when a parameter doesn't have a type annotation. """ if param.annotation != inspect._empty: return param.annotation elif param.default is None: return parser_helper else: type_of = type(param.default) if type_of is bool: return lambda value: bool(parser_helper(value)) return type_of
Example #30
Source File: core.py From CrossHair with MIT License | 5 votes |
def get_constructor_params(cls: Type) -> Iterable[inspect.Parameter]: # TODO inspect __new__ as well init_fn = cls.__init__ if init_fn is object.__init__: return () init_sig = get_resolved_signature(init_fn) return list(init_sig.parameters.values())[1:]