我们从Python开源项目中,提取了以下30个代码示例,用于说明如何使用inspect.Signature()。
def _get_workflow_from_task(task): """ Looks for an instance of `Workflow` linked to the task or a method of `Workflow` among the done callbacks of the asyncio task. Returns None if not found. If the task was triggered from within a workflow it MUST have a `workflow` attribute that points to it and at least one done callback that is a method of `Workflow`. """ if isinstance(task, TukioTask): workflow = task.workflow if workflow: return workflow for cb in task._callbacks: # inspect.getcallargs() gives access to the implicit 'self' arg of # the bound method but it is marked as deprecated since # Python 3.5.1 and the new `inspect.Signature` object does NOT do # the job :(( if inspect.ismethod(cb): inst = cb.__self__ elif isinstance(cb, functools.partial): try: inst = cb.func.__self__ except AttributeError: continue else: continue if isinstance(inst, Workflow): return inst return None
def make_sig(*names): parms = [Parameter(name, Parameter.POSITIONAL_OR_KEYWORD) for name in names] return Signature(parms)
def __init__( self, module: str, qualname: str, kind: FunctionKind, sig: inspect.Signature, is_async: bool = False ) -> None: self.module = module self.qualname = qualname self.kind = kind self.signature = sig self.is_async = is_async
def from_callable(cls, func: Callable, kind: FunctionKind = None) -> 'FunctionDefinition': kind = FunctionKind.from_callable(func) sig = inspect.Signature.from_callable(func) is_async = asyncio.iscoroutinefunction(func) return FunctionDefinition(func.__module__, func.__qualname__, kind, sig, is_async)
def get_imports_for_annotation(anno: Any) -> ImportMap: """Return the imports (module, name) needed for the type in the annotation""" imports = ImportMap() if ( anno is inspect.Parameter.empty or anno is inspect.Signature.empty or not isinstance(anno, (type, _Any, _Union)) or anno.__module__ == 'builtins' ): return imports if isinstance(anno, _Any): imports['typing'].add('Any') elif _is_optional(anno): imports['typing'].add('Optional') elem_type = _get_optional_elem(anno) elem_imports = get_imports_for_annotation(elem_type) imports.merge(elem_imports) elif isinstance(anno, (_Union, GenericMeta)): if isinstance(anno, _Union): imports['typing'].add('Union') else: name = _get_import_for_qualname(anno.__qualname__) imports[anno.__module__].add(name) elem_types = anno.__args__ or [] for et in elem_types: elem_imports = get_imports_for_annotation(et) imports.merge(elem_imports) else: name = _get_import_for_qualname(anno.__qualname__) imports[anno.__module__].add(name) return imports
def get_imports_for_signature(sig: inspect.Signature) -> ImportMap: """Return the imports (module, name) needed for all types in annotations""" imports = ImportMap() for param in sig.parameters.values(): param_imports = get_imports_for_annotation(param.annotation) imports.merge(param_imports) return_imports = get_imports_for_annotation(sig.return_annotation) imports.merge(return_imports) return imports
def update_signature_args(sig: inspect.Signature, arg_types: Dict[str, type], has_self: bool) -> inspect.Signature: """Update argument annotations with the supplied types""" params = [] for arg_idx, name in enumerate(sig.parameters): param = sig.parameters[name] typ = arg_types.get(name) # Don't touch pre-existing annotations and leave self un-annotated if (typ is not None) and \ (param.annotation is inspect.Parameter.empty) and \ ((not has_self) or (arg_idx != 0)): param = param.replace(annotation=typ) params.append(param) return sig.replace(parameters=params)
def has_unparsable_defaults(sig: inspect.Signature) -> bool: """Return whether or not the reprs for all defaults in the signature are valid python expressions""" for param in sig.parameters.values(): if param.default is inspect.Parameter.empty: continue try: parser.expr(repr(param.default)) except SyntaxError: return True return False
def __init__( self, name: str, signature: inspect.Signature, kind: FunctionKind, strip_modules: Iterable[str] = None, is_async: bool = False ) -> None: self.name = name self.signature = signature self.kind = kind self.strip_modules = strip_modules or [] self.is_async = is_async
def signature_without_unbound_args(func): sig = inspect.signature(func) params = [param for param in sig.parameters.values() if param.kind not in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD)] return inspect.Signature(params)
def test_signature_object(self): S = inspect.Signature P = inspect.Parameter self.assertEqual(str(S()), '()') def test(po, pk, *args, ko, **kwargs): pass sig = inspect.signature(test) po = sig.parameters['po'].replace(kind=P.POSITIONAL_ONLY) pk = sig.parameters['pk'] args = sig.parameters['args'] ko = sig.parameters['ko'] kwargs = sig.parameters['kwargs'] S((po, pk, args, ko, kwargs)) with self.assertRaisesRegex(ValueError, 'wrong parameter order'): S((pk, po, args, ko, kwargs)) with self.assertRaisesRegex(ValueError, 'wrong parameter order'): S((po, args, pk, ko, kwargs)) with self.assertRaisesRegex(ValueError, 'wrong parameter order'): S((args, po, pk, ko, kwargs)) with self.assertRaisesRegex(ValueError, 'wrong parameter order'): S((po, pk, args, kwargs, ko)) kwargs2 = kwargs.replace(name='args') with self.assertRaisesRegex(ValueError, 'duplicate parameter name'): S((po, pk, args, kwargs2, ko))
def test_signature_on_non_function(self): with self.assertRaisesRegex(TypeError, 'is not a callable object'): inspect.signature(42) with self.assertRaisesRegex(TypeError, 'is not a Python function'): inspect.Signature.from_function(42)
def construct_signature(self): """Construct a pretty function signature for dynamic commands. The inspect modules Parameter and Signature are fully supported in Python 3.5, broken in 3.4, and missing in 2.7. Returns: Signature object for command. """ param_dict = OrderedDict() for param, default in sorted(self.get_all_valid_params().items()): new_param = Parameter(param, Parameter.KEYWORD_ONLY, default=default) self.log.debug('New parameter: %s', new_param) param_dict[new_param] = param self.log.debug('Parameter dictionary growing: %s', param_dict) self.log.debug('Parameter dictionary: %s', param_dict) new_signature = Signature(parameters=param_dict) self.log.debug('New signature: %s', new_signature) return new_signature # TODO: When Python 2.7 support is removed, api_map kwarg should be removed
def test_getfullargspec_signature_attr(self): def test(): pass spam_param = inspect.Parameter('spam', inspect.Parameter.POSITIONAL_ONLY) test.__signature__ = inspect.Signature(parameters=(spam_param,)) self.assertFullArgSpecEquals(test, args_e=['spam'], formatted='(spam)')
def test_signature_from_builtin_errors(self): with self.assertRaisesRegex(TypeError, 'is not a Python builtin'): inspect.Signature.from_builtin(42)
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)')
def sig_from_params(*args): return(inspect.Signature(list(args)))
def make_sig(*names): parms = [Parameter(name,Parameter.POSITIONAL_OR_KEYWORD) for name in names] return Signature(parms)
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) # apply_defaults ba.arguments = ChainMap( ba.arguments, {name: param.default for name, param in default_sel_sig.parameters.items() if param.default is not param.empty}) sel = Selection(*ba.args, **ba.kwargs) return func(sel, **extra_kw) wrapper.__signature__ = Signature( list(sel_sig.parameters.values()) + wrapped_kwonly_params) return wrapper
def test_signature_object(self): S = inspect.Signature P = inspect.Parameter self.assertEqual(str(S()), '()') def test(po, pk, pod=42, pkd=100, *args, ko, **kwargs): pass sig = inspect.signature(test) po = sig.parameters['po'].replace(kind=P.POSITIONAL_ONLY) pod = sig.parameters['pod'].replace(kind=P.POSITIONAL_ONLY) pk = sig.parameters['pk'] pkd = sig.parameters['pkd'] args = sig.parameters['args'] ko = sig.parameters['ko'] kwargs = sig.parameters['kwargs'] S((po, pk, args, ko, kwargs)) with self.assertRaisesRegex(ValueError, 'wrong parameter order'): S((pk, po, args, ko, kwargs)) with self.assertRaisesRegex(ValueError, 'wrong parameter order'): S((po, args, pk, ko, kwargs)) with self.assertRaisesRegex(ValueError, 'wrong parameter order'): S((args, po, pk, ko, kwargs)) with self.assertRaisesRegex(ValueError, 'wrong parameter order'): S((po, pk, args, kwargs, ko)) kwargs2 = kwargs.replace(name='args') with self.assertRaisesRegex(ValueError, 'duplicate parameter name'): S((po, pk, args, kwargs2, ko)) with self.assertRaisesRegex(ValueError, 'follows default argument'): S((pod, po)) with self.assertRaisesRegex(ValueError, 'follows default argument'): S((po, pkd, pk)) with self.assertRaisesRegex(ValueError, 'follows default argument'): S((pkd, pk))
def test_signature_from_functionlike_object(self): def func(a,b, *args, kwonly=True, kwonlyreq, **kwargs): pass class funclike: # Has to be callable, and have correct # __code__, __annotations__, __defaults__, __name__, # and __kwdefaults__ attributes def __init__(self, func): self.__name__ = func.__name__ self.__code__ = func.__code__ self.__annotations__ = func.__annotations__ self.__defaults__ = func.__defaults__ self.__kwdefaults__ = func.__kwdefaults__ self.func = func def __call__(self, *args, **kwargs): return self.func(*args, **kwargs) sig_func = inspect.Signature.from_function(func) sig_funclike = inspect.Signature.from_function(funclike(func)) self.assertEqual(sig_funclike, sig_func) sig_funclike = inspect.signature(funclike(func)) self.assertEqual(sig_funclike, sig_func) # If object is not a duck type of function, then # signature will try to get a signature for its '__call__' # method fl = funclike(func) del fl.__defaults__ self.assertEqual(self.signature(fl), ((('args', ..., ..., "var_positional"), ('kwargs', ..., ..., "var_keyword")), ...)) # Test with cython-like builtins: _orig_isdesc = inspect.ismethoddescriptor def _isdesc(obj): if hasattr(obj, '_builtinmock'): return True return _orig_isdesc(obj) with unittest.mock.patch('inspect.ismethoddescriptor', _isdesc): builtin_func = funclike(func) # Make sure that our mock setup is working self.assertFalse(inspect.ismethoddescriptor(builtin_func)) builtin_func._builtinmock = True self.assertTrue(inspect.ismethoddescriptor(builtin_func)) self.assertEqual(inspect.signature(builtin_func), sig_func)
def get_signature(name, mapped_name, signature, manual_sigs, env): if isinstance(signature, str): if signature in manual_sigs: signature = inspect.Signature(manual_sigs[signature]) else: raise ValueError('signature error - specified signature not found') if signature is None: # establish function try: fun = eval(mapped_name, env) except: raise ValueError("%s() was not found." % mapped_name) # first go through manual sigs # try to get signature try: if name in manual_sigs: signature = inspect.Signature(manual_sigs[name]) else: # it might be a method, and we have to find the general method name if "." in mapped_name: els = name.split(".") try: els[0] = type(eval(els[0], env)).__name__ generic_name = ".".join(els[:]) except: raise ValueError('signature error - cannot convert call') if generic_name in manual_sigs: signature = inspect.Signature(manual_sigs[generic_name]) else: raise ValueError('signature error - %s not in builtins' % generic_name) else: raise ValueError('manual signature not found') except: try: signature = inspect.signature(fun) except: raise ValueError('signature error - cannot determine signature') return signature # Get the signature of a function based on an object inside the process