Python inspect.Signature() Examples

The following are 30 code examples of inspect.Signature(). 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: _pick_info.py    From mplcursors with MIT License 7 votes vote down vote up
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 
Example #2
Source File: usage_logger.py    From koalas with Apache License 2.0 6 votes vote down vote up
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) 
Example #3
Source File: typed_struct.py    From easypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #4
Source File: models.py    From symfit with GNU General Public License v2.0 6 votes vote down vote up
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)) 
Example #5
Source File: adapt.py    From cornerwise with MIT License 6 votes vote down vote up
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 
Example #6
Source File: function_utils.py    From federated with Apache License 2.0 6 votes vote down vote up
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)))) 
Example #7
Source File: test_inspect.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
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 #8
Source File: exporters.py    From sauron-engine with MIT License 6 votes vote down vote up
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 
Example #9
Source File: _resources.py    From civis-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #10
Source File: _base.py    From argo-python-dsl with Apache License 2.0 6 votes vote down vote up
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 
Example #11
Source File: test_inspect.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
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 #12
Source File: _unpack.py    From undictify with MIT License 6 votes vote down vote up
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} 
Example #13
Source File: usage_logger.py    From koalas with Apache License 2.0 6 votes vote down vote up
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) 
Example #14
Source File: _callable_docstr.py    From MIA-Dictionary-Addon with GNU General Public License v3.0 5 votes vote down vote up
def callable_signature(callable):
    # Create an inspect.Signature for an PyObjC callable
    # both objc.function and objc.native_selector only support positional
    # arguments, and not keyword arguments.
    try:
        metadata = callable.__metadata__()
    except objc.internal_error:
        # This can happen with some private methods with undocumented
        # characters in type encodings
        return None

    ismethod = isinstance(callable, objc.selector)

    if ismethod:
        args = metadata["arguments"][
            2:
        ]  # Skip 'self' and 'selector' implicit arguments
    else:
        args = metadata["arguments"]

    parameters = []
    for idx, arg in enumerate(args):
        p_name = "arg%d" % (idx,)
        parameters.append(
            inspect.Parameter(p_name, inspect.Parameter.POSITIONAL_ONLY)
        )

    return inspect.Signature(parameters) 
Example #15
Source File: dsp.py    From schedula with European Union Public License 1.1 5 votes vote down vote up
def __signature__(self):
        import inspect
        dfl, p = self.dsp.default_values, []
        for name in self.inputs or ():
            par = inspect.Parameter('par', inspect._POSITIONAL_OR_KEYWORD)
            par._name = name
            if name in dfl:
                par._default = dfl[name]['value']
            p.append(par)
        if self.var_keyword:
            p.append(inspect.Parameter(self.var_keyword, inspect._VAR_KEYWORD))
        return inspect.Signature(p, __validate_parameters__=False) 
Example #16
Source File: _decorators.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #17
Source File: core.py    From CrossHair with MIT License 5 votes vote down vote up
def get_resolved_signature(fn: Callable) -> inspect.Signature:
    wrapped = IdentityWrapper(fn)
    if wrapped not in _RESOLVED_FNS:
        _RESOLVED_FNS.add(wrapped)
        try:
            fn.__annotations__ = get_type_hints(fn)
        except Exception as e:
            debug('Could not resolve annotations on', fn, ':', e)
    return inspect.signature(fn) 
Example #18
Source File: condition_parser.py    From CrossHair with MIT License 5 votes vote down vote up
def set_self_type(sig: inspect.Signature, self_type: type) -> inspect.Signature:
    newparams = list(sig.parameters.values())
    newparams[0] = newparams[0].replace(annotation=self_type)
    return inspect.Signature(newparams, return_annotation=sig.return_annotation) 
Example #19
Source File: condition_parser.py    From CrossHair with MIT License 5 votes vote down vote up
def resolve_signature(fn: Callable) -> Optional[inspect.Signature]:
    ''' Resolve type annotations with get_type_hints '''
    try:
        sig = inspect.signature(fn)
    except ValueError:
        return None
    type_hints = get_type_hints(fn, fn_globals(fn))
    params = sig.parameters.values()
    newparams = []
    for name, param in sig.parameters.items():
        if name in type_hints:
            param = param.replace(annotation=type_hints[name])
        newparams.append(param)
    newreturn = type_hints.get('return', sig.return_annotation)
    return inspect.Signature(newparams, return_annotation=newreturn) 
Example #20
Source File: config.py    From panel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _apply_signatures(self):
        from inspect import Parameter, Signature
        from .viewable import Viewable

        descendants = param.concrete_descendents(Viewable)
        for cls in reversed(list(descendants.values())):
            if cls.__doc__.startswith('params'):
                prefix = cls.__doc__.split('\n')[0]
                cls.__doc__ = cls.__doc__.replace(prefix, '')
            sig = inspect.signature(cls.__init__)
            sig_params = list(sig.parameters.values())
            if not sig_params or sig_params[-1] != Parameter('params', Parameter.VAR_KEYWORD):
                continue
            parameters = sig_params[:-1]

            processed_kws, keyword_groups = set(), []
            for cls in reversed(cls.mro()):
                keyword_group = []
                for (k, v) in sorted(cls.__dict__.items()):
                    if (isinstance(v, param.Parameter) and k not in processed_kws
                        and not v.readonly):
                        keyword_group.append(k)
                        processed_kws.add(k)
                keyword_groups.append(keyword_group)

            parameters += [
                Parameter(name, Parameter.KEYWORD_ONLY)
                for kws in reversed(keyword_groups) for name in kws
                if name not in sig.parameters
            ]
            parameters.append(Parameter('kwargs', Parameter.VAR_KEYWORD))
            cls.__init__.__signature__ = Signature(
                parameters, return_annotation=sig.return_annotation
            )


#---------------------------------------------------------------------
# Private API
#--------------------------------------------------------------------- 
Example #21
Source File: _decorators.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
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 
Example #22
Source File: settings.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _generate_signature(cls):
        from inspect import Signature, Parameter
        keywords = ['backend', 'fig', 'holomap', 'widgets', 'fps', 'max_frames',
                    'size', 'dpi', 'filename', 'info', 'css', 'widget_location']
        return Signature([Parameter(kw, Parameter.KEYWORD_ONLY) for kw in keywords]) 
Example #23
Source File: __init__.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _update_backend(cls, backend):

        if cls.__original_docstring__ is None:
            cls.__original_docstring__ = cls.__doc__

        all_keywords = set()
        element_keywords = cls._element_keywords(backend)
        for element, keywords in element_keywords.items():
            with param.logging_level('CRITICAL'):
                all_keywords |= set(keywords)
                setattr(cls, element,
                        cls._create_builder(element, keywords))

        filtered_keywords = [k for k in all_keywords if k not in cls._no_completion]
        sorted_kw_set = sorted(set(filtered_keywords))
        if sys.version_info.major == 2:
            kws = ', '.join('{opt}=None'.format(opt=opt) for opt in sorted_kw_set)
            old_doc = cls.__original_docstring__.replace(
                'params(strict=Boolean, name=String)','')
            cls.__doc__ = '\n    opts({kws})'.format(kws=kws) + old_doc
        else:
            from inspect import Parameter, Signature
            signature = Signature([Parameter('args', Parameter.VAR_POSITIONAL)]
                                  + [Parameter(kw, Parameter.KEYWORD_ONLY)
                                     for kw in sorted_kw_set])
            cls.__init__.__signature__ = signature 
Example #24
Source File: collections.py    From rlpyt with MIT License 5 votes vote down vote up
def __init__(self, typename, fields):
        if not isinstance(typename, str):
            raise TypeError(f"type name must be string, not {type(typename)}")

        if isinstance(fields, str):
            spaces = any([whitespace in fields for whitespace in string.whitespace])
            commas = "," in fields
            if spaces and commas:
                raise ValueError(f"Single string fields={fields} cannot have both spaces and commas.")
            elif spaces:
                fields = fields.split()
            elif commas:
                fields = fields.split(",")
            else:
                # If there are neither spaces nor commas, then there is only one field.
                fields = (fields,)
        fields = tuple(fields)

        for field in fields:
            if not isinstance(field, str):
                raise ValueError(f"field names must be strings: {field}")
            if field.startswith("_"):
                raise ValueError(f"field names cannot start with an "
                                 f"underscore: {field}")
            if field in ("index", "count"):
                raise ValueError(f"can't name field 'index' or 'count'")
        self.__dict__["_typename"] = typename
        self.__dict__["_fields"] = fields
        self.__dict__["_signature"] = Sig(Param(field,
            Param.POSITIONAL_OR_KEYWORD) for field in fields) 
Example #25
Source File: builtin.py    From bfg9000 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def bind(self, context):
        @functools.wraps(self._fn)
        def wrapper(*args, **kwargs):
            return self._fn(context, *args, **kwargs)

        sig = inspect.signature(wrapper)
        params = list(sig.parameters.values())[self.builtin_bound:]
        wrapper.__signature__ = inspect.Signature(params)
        return wrapper 
Example #26
Source File: test_functions.py    From sidekick with MIT License 5 votes vote down vote up
def test_signature(self):
        sig: Signature = sk.signature(lambda x, y: None)
        assert sig.return_annotation == sig.empty
        assert list(sig.parameters) == ["x", "y"] 
Example #27
Source File: core_functions.py    From sidekick with MIT License 5 votes vote down vote up
def signature(func: Callable) -> inspect.Signature:
    """
    Return the signature of a function.
    """

    if hasattr(func, "signature"):
        return func.signature()

    return inspect.Signature.from_callable(func) 
Example #28
Source File: _decorators.py    From recruit with Apache License 2.0 5 votes vote down vote up
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 
Example #29
Source File: class_validators.py    From pydantic with MIT License 5 votes vote down vote up
def _generic_validator_cls(validator: AnyCallable, sig: 'Signature', args: Set[str]) -> 'ValidatorCallable':
    # assume the first argument is value
    has_kwargs = False
    if 'kwargs' in args:
        has_kwargs = True
        args -= {'kwargs'}

    if not args.issubset(all_kwargs):
        raise ConfigError(
            f'Invalid signature for validator {validator}: {sig}, should be: '
            f'(cls, value, values, config, field), "values", "config" and "field" are all optional.'
        )

    if has_kwargs:
        return lambda cls, v, values, field, config: validator(cls, v, values=values, field=field, config=config)
    elif args == set():
        return lambda cls, v, values, field, config: validator(cls, v)
    elif args == {'values'}:
        return lambda cls, v, values, field, config: validator(cls, v, values=values)
    elif args == {'field'}:
        return lambda cls, v, values, field, config: validator(cls, v, field=field)
    elif args == {'config'}:
        return lambda cls, v, values, field, config: validator(cls, v, config=config)
    elif args == {'values', 'field'}:
        return lambda cls, v, values, field, config: validator(cls, v, values=values, field=field)
    elif args == {'values', 'config'}:
        return lambda cls, v, values, field, config: validator(cls, v, values=values, config=config)
    elif args == {'field', 'config'}:
        return lambda cls, v, values, field, config: validator(cls, v, field=field, config=config)
    else:
        # args == {'values', 'field', 'config'}
        return lambda cls, v, values, field, config: validator(cls, v, values=values, field=field, config=config) 
Example #30
Source File: element.py    From idom with MIT License 5 votes vote down vote up
def _extract_signature(
    function: Callable[..., Any]
) -> Tuple[inspect.Signature, Optional[str], Optional[str]]:
    sig = inspect.signature(function)
    var_positional: Optional[str] = None
    var_keyword: Optional[str] = None

    for param in sig.parameters.values():
        if param.kind is inspect.Parameter.VAR_POSITIONAL:
            var_positional = param.name
        elif param.kind is inspect.Parameter.VAR_KEYWORD:
            var_keyword = param.name

    return sig, var_positional, var_keyword