當前位置: 首頁>>代碼示例>>Python>>正文


Python inspect.Signature方法代碼示例

本文整理匯總了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 
開發者ID:anntzer,項目名稱:mplcursors,代碼行數:25,代碼來源:_pick_info.py

示例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 
開發者ID:codeforboston,項目名稱:cornerwise,代碼行數:19,代碼來源:adapt.py

示例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)))) 
開發者ID:tensorflow,項目名稱:federated,代碼行數:22,代碼來源:function_utils.py

示例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)) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:25,代碼來源:test_inspect.py

示例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) 
開發者ID:civisanalytics,項目名稱:civis-python,代碼行數:26,代碼來源:_resources.py

示例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 
開發者ID:CermakM,項目名稱:argo-python-dsl,代碼行數:24,代碼來源:_base.py

示例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} 
開發者ID:Dobiasd,項目名稱:undictify,代碼行數:18,代碼來源:_unpack.py

示例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) 
開發者ID:databricks,項目名稱:koalas,代碼行數:25,代碼來源:usage_logger.py

示例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) 
開發者ID:databricks,項目名稱:koalas,代碼行數:26,代碼來源:usage_logger.py

示例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 
開發者ID:blurg,項目名稱:sauron-engine,代碼行數:25,代碼來源:exporters.py

示例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)) 
開發者ID:tBuLi,項目名稱:symfit,代碼行數:18,代碼來源:models.py

示例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 
開發者ID:weka-io,項目名稱:easypy,代碼行數:25,代碼來源:typed_struct.py

示例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 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:29,代碼來源:_decorators.py

示例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 
開發者ID:tiangolo,項目名稱:fastapi,代碼行數:16,代碼來源:utils.py

示例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) 
開發者ID:standy66,項目名稱:purerpc,代碼行數:17,代碼來源:server.py


注:本文中的inspect.Signature方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。