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: test_alter_axes.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_set_axis_prior_to_deprecation_signature(self):
        df = DataFrame({'A': [1.1, 2.2, 3.3],
                        'B': [5.0, 6.1, 7.2],
                        'C': [4.4, 5.5, 6.6]},
                       index=[2010, 2011, 2012])

        expected = {0: df.copy(),
                    1: df.copy()}
        expected[0].index = list('abc')
        expected[1].columns = list('abc')
        expected['index'] = expected[0]
        expected['columns'] = expected[1]

        # old signature
        for axis in expected:
            with tm.assert_produces_warning(FutureWarning):
                result = df.set_axis(axis, list('abc'), inplace=False)
            tm.assert_frame_equal(result, expected[axis]) 
Example #2
Source File: constraints.py    From matchpy with MIT License 6 votes vote down vote up
def __init__(self, constraint: Callable[..., bool]) -> None:
        """
        Args:
            constraint:
                The constraint callback.

        Raises:
            ValueError:
                If the callback has positional-only or variable parameters (\*args and \*\*kwargs).
        """
        self.constraint = constraint
        signature = inspect.signature(constraint)

        self._variables = OrderedDict()

        for param in signature.parameters.values():
            if param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD or param.kind == inspect.Parameter.KEYWORD_ONLY:
                self._variables[param.name] = param.name
            elif param.kind == inspect.Parameter.VAR_KEYWORD:
                raise ValueError("Constraint cannot have variable keyword arguments ({})".format(param.name))
            else:
                raise ValueError(
                    "Constraint cannot have positional-only or variable positional arguments ({})".format(param.name)
                ) 
Example #3
Source File: argtools.py    From dataflow with Apache License 2.0 6 votes vote down vote up
def map_arg(**maps):
    """
    Apply a mapping on certain argument before calling the original function.

    Args:
        maps (dict): {argument_name: map_func}
    """
    def deco(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            # getcallargs was deprecated since 3.5
            sig = inspect.signature(func)
            argmap = sig.bind_partial(*args, **kwargs).arguments
            for k, map_func in maps.items():
                if k in argmap:
                    argmap[k] = map_func(argmap[k])
            return func(**argmap)
        return wrapper
    return deco 
Example #4
Source File: client.py    From python-slackclient with MIT License 6 votes vote down vote up
def _validate_callback(callback):
        """Checks if the specified callback is callable and accepts a kwargs param.

        Args:
            callback (obj): Any object or a list of objects that can be called.
                e.g. <function say_hello at 0x101234567>

        Raises:
            SlackClientError: The specified callback is not callable.
            SlackClientError: The callback must accept keyword arguments (**kwargs).
        """

        cb_name = callback.__name__ if hasattr(callback, "__name__") else callback
        if not callable(callback):
            msg = "The specified callback '{}' is not callable.".format(cb_name)
            raise client_err.SlackClientError(msg)
        callback_params = inspect.signature(callback).parameters.values()
        if not any(
            param for param in callback_params if param.kind == param.VAR_KEYWORD
        ):
            msg = "The callback '{}' must accept keyword arguments (**kwargs).".format(
                cb_name
            )
            raise client_err.SlackClientError(msg) 
Example #5
Source File: modules.py    From Nest with MIT License 6 votes vote down vote up
def __init__(self, func: Callable, meta: Dict[str, object], params: dict = {}) -> None:
        # module func
        self.func = func
        self.__name__ = func.__name__
        # module signature
        self.sig = inspect.signature(func)
        # meta information
        self.meta = U.merge_dict(dict(), meta, union=True)
        # record module params
        self.params = U.merge_dict(dict(), params, union=True)
        # init module context
        for k, v in self.sig.parameters.items():
            if k =='ctx' and issubclass(v.annotation, Context):
                self.params[k] = v.annotation()
            break
        # check module
        self._check_definition() 
Example #6
Source File: typing.py    From pytorch_geometric with MIT License 6 votes vote down vote up
def parse_types(func: Callable) -> List[Tuple[Dict[str, str], str]]:
    source = inspect.getsource(func)
    signature = inspect.signature(func)

    # Parse `# type: (...) -> ...` annotation. Note that it is allowed to pass
    # multiple `# type:` annotations in `forward()`.
    iterator = re.finditer(r'#\s*type:\s*\((.*)\)\s*->\s*(.*)\s*\n', source)
    matches = list(iterator)

    if len(matches) > 0:
        out = []
        args = list(signature.parameters.keys())
        for match in matches:
            arg_types_repr, return_type = match.groups()
            arg_types = split_types_repr(arg_types_repr)
            arg_types = OrderedDict((k, v) for k, v in zip(args, arg_types))
            return_type = return_type.split('#')[0].strip()
            out.append((arg_types, return_type))
        return out

    # Alternatively, parse annotations using the inspected signature.
    else:
        ps = signature.parameters
        arg_types = OrderedDict((k, param_type_repr(v)) for k, v in ps.items())
        return [(arg_types, return_type_repr(signature))] 
Example #7
Source File: singleton.py    From celery-singleton with MIT License 6 votes vote down vote up
def generate_lock(self, task_name, task_args=None, task_kwargs=None):
        unique_on = self.unique_on
        task_args = task_args or []
        task_kwargs = task_kwargs or {}
        if unique_on:
            if isinstance(unique_on, str):
                unique_on = [unique_on]
            sig = inspect.signature(self.run)
            bound = sig.bind(*task_args, **task_kwargs).arguments

            unique_args = []
            unique_kwargs = {key: bound[key] for key in unique_on}
        else:
            unique_args = task_args
            unique_kwargs = task_kwargs
        return util.generate_lock(
            task_name,
            unique_args,
            unique_kwargs,
            key_prefix=self.singleton_config.key_prefix,
        ) 
Example #8
Source File: core.py    From discord.py with MIT License 6 votes vote down vote up
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 #9
Source File: data_augmentation_chain_original_ssd.py    From data_generator_object_detection_2d with GNU General Public License v3.0 6 votes vote down vote up
def __call__(self, image, labels, return_inverter=False):
        self.expand.labels_format = self.labels_format
        self.random_crop.labels_format = self.labels_format
        self.random_flip.labels_format = self.labels_format
        self.resize.labels_format = self.labels_format

        inverters = []

        for transform in self.sequence:
            if return_inverter and ('return_inverter' in inspect.signature(transform).parameters):
                image, labels, inverter = transform(image, labels, return_inverter=True)
                inverters.append(inverter)
            else:
                image, labels = transform(image, labels)

        if return_inverter:
            return image, labels, inverters[::-1]
        else:
            return image, labels 
Example #10
Source File: utils.py    From uplink with MIT License 6 votes vote down vote up
def get_call_args(f, *args, **kwargs):
        sig = signature(f)
        arguments = sig.bind(*args, **kwargs).arguments
        # apply defaults:
        new_arguments = []
        for name, param in sig.parameters.items():
            try:
                new_arguments.append((name, arguments[name]))
            except KeyError:
                if param.default is not param.empty:
                    val = param.default
                elif param.kind is param.VAR_POSITIONAL:
                    val = ()
                elif param.kind is param.VAR_KEYWORD:
                    val = {}
                else:
                    continue
                new_arguments.append((name, val))
        return collections.OrderedDict(new_arguments) 
Example #11
Source File: __init__.py    From recruit with Apache License 2.0 6 votes vote down vote up
def signature(f):
        sig = inspect.signature(f)
        args = [
            p.name for p in sig.parameters.values()
            if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
        ]
        varargs = [
            p.name for p in sig.parameters.values()
            if p.kind == inspect.Parameter.VAR_POSITIONAL
        ]
        varargs = varargs[0] if varargs else None
        keywords = [
            p.name for p in sig.parameters.values()
            if p.kind == inspect.Parameter.VAR_KEYWORD
        ]
        keywords = keywords[0] if keywords else None
        defaults = [
            p.default for p in sig.parameters.values()
            if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
            and p.default is not p.empty
        ] or None
        argspec = namedtuple('Signature', ['args', 'defaults',
                                           'varargs', 'keywords'])
        return argspec(args, defaults, varargs, keywords) 
Example #12
Source File: cmdutils.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def __call__(self, func: typing.Callable) -> typing.Callable:
        funcname = func.__name__

        if self._argname not in inspect.signature(func).parameters:
            raise ValueError("{} has no argument {}!".format(funcname,
                                                             self._argname))
        if not hasattr(func, 'qute_args'):
            func.qute_args = {}  # type: ignore[attr-defined]
        elif func.qute_args is None:  # type: ignore[attr-defined]
            raise ValueError("@cmdutils.argument got called above (after) "
                             "@cmdutils.register for {}!".format(funcname))

        arginfo = command.ArgInfo(**self._kwargs)
        func.qute_args[self._argname] = arginfo  # type: ignore[attr-defined]

        return func 
Example #13
Source File: entitycache.py    From Telethon with MIT License 6 votes vote down vote up
def _fill():
    for name in dir(types):
        update = getattr(types, name)
        if getattr(update, 'SUBCLASS_OF_ID', None) == 0x9f89304e:
            cid = update.CONSTRUCTOR_ID
            sig = inspect.signature(update.__init__)
            for param in sig.parameters.values():
                vec = _has_field.get((param.name, param.annotation))
                if vec is not None:
                    vec.append(cid)

    # Future-proof check: if the documentation format ever changes
    # then we won't be able to pick the update types we are interested
    # in, so we must make sure we have at least an update for each field
    # which likely means we are doing it right.
    if not all(_has_field.values()):
        raise RuntimeError('FIXME: Did the init signature or updates change?')


# We use a function to avoid cluttering the globals (with name/update/cid/doc) 
Example #14
Source File: base.py    From briefcase with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_config(klass, config, msg):
    try:
        return klass(**config)
    except TypeError:
        # Inspect the GlobalConfig constructor to find which
        # parameters are required and don't have a default
        # value.
        required_args = {
            name
            for name, param in inspect.signature(klass.__init__).parameters.items()
            if param.default == inspect._empty
            and name not in {'self', 'kwargs'}
        }
        missing_args = required_args - config.keys()
        missing = ', '.join(
            "'{arg}'".format(arg=arg)
            for arg in sorted(missing_args)
        )
        raise BriefcaseConfigError(
            "{msg} is incomplete (missing {missing})".format(
                msg=msg,
                missing=missing
            )
        ) 
Example #15
Source File: test_dataclasses.py    From dataclasses with Apache License 2.0 6 votes vote down vote up
def test_field_named_self(self):
        @dataclass
        class C:
            self: str
        c=C('foo')
        self.assertEqual(c.self, 'foo')

        # Make sure the first parameter is not named 'self'.
        sig = inspect.signature(C.__init__)
        first = next(iter(sig.parameters))
        self.assertNotEqual('self', first)

        # But we do use 'self' if no field named self.
        @dataclass
        class C:
            selfx: str

        # Make sure the first parameter is named 'self'.
        sig = inspect.signature(C.__init__)
        first = next(iter(sig.parameters))
        self.assertEqual('self', first) 
Example #16
Source File: engine.py    From UnsupervisedGeometryAwareRepresentationLearning with GNU General Public License v3.0 6 votes vote down vote up
def _check_signature(self, fn, fn_description, *args, **kwargs):
        exception_msg = None

        if IS_PYTHON2:
            try:
                callable_ = fn if hasattr(fn, '__name__') else fn.__call__
                inspect.getcallargs(callable_, self, *args, **kwargs)
            except TypeError as exc:
                spec = inspect.getargspec(callable_)
                fn_params = list(spec.args)
                exception_msg = str(exc)
        else:
            signature = inspect.signature(fn)
            try:
                signature.bind(self, *args, **kwargs)
            except TypeError as exc:
                fn_params = list(signature.parameters)
                exception_msg = str(exc)

        if exception_msg:
            passed_params = [self] + list(args) + list(kwargs)
            raise ValueError("Error adding {} '{}': "
                             "takes parameters {} but will be called with {} "
                             "({})".format(
                                 fn, fn_description, fn_params, passed_params, exception_msg)) 
Example #17
Source File: interfaces_annotations.py    From Expert-Python-Programming_Second-Edition with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def ensure_interface(function):
    signature = inspect.signature(function)
    parameters = signature.parameters

    @wraps(function)
    def wrapped(*args, **kwargs):
        bound = signature.bind(*args, **kwargs)
        for name, value in bound.arguments.items():
            annotation = parameters[name].annotation

            if not isinstance(annotation, ABCMeta):
                continue

            if not isinstance(value, annotation):
                raise TypeError(
                    "{} does not implement {} interface"
                    "".format(value, annotation)

                )

        function(*args, **kwargs)

    return wrapped 
Example #18
Source File: hooks.py    From schemathesis with MIT License 6 votes vote down vote up
def _validate_hook(self, name: str, hook: Callable) -> None:
        """Basic validation for hooks being registered."""
        spec = self._specs.get(name)
        if spec is None:
            raise TypeError(f"There is no hook with name '{name}'")
        # Some hooks are not present on all levels. We need to avoid registering hooks on wrong levels
        if self.scope not in spec.scopes:
            scopes = ", ".join(scope.name for scope in spec.scopes)
            raise ValueError(
                f"Can not register hook '{name}' on {self.scope.name} scope dispatcher. "
                f"Use a dispatcher with {scopes} scope(s) instead"
            )
        signature = inspect.signature(hook)
        if len(signature.parameters) != len(spec.signature.parameters):
            raise TypeError(
                f"Hook '{name}' takes {len(spec.signature.parameters)} arguments but {len(signature.parameters)} is defined"
            ) 
Example #19
Source File: command.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
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 #20
Source File: core.py    From discord.py with MIT License 6 votes vote down vote up
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 #21
Source File: __init__.py    From recruit with Apache License 2.0 5 votes vote down vote up
def signature(f):
        return inspect.getargspec(f) 
Example #22
Source File: test_docstring_parameters.py    From celer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_args(function, varargs=False):
        params = inspect.signature(function).parameters
        args = [key for key, param in params.items()
                if param.kind not in (param.VAR_POSITIONAL, param.VAR_KEYWORD)]
        if varargs:
            varargs = [param.name for param in params.values()
                       if param.kind == param.VAR_POSITIONAL]
            if len(varargs) == 0:
                varargs = None
            return args, varargs
        else:
            return args 
Example #23
Source File: scaled.py    From geoopt with Apache License 2.0 5 votes vote down vote up
def rescale(function, scaling_info):
    if scaling_info is ScalingInfo.NotCompatible:

        @functools.wraps(functools)
        def stub(self, *args, **kwargs):
            raise NotImplementedError(
                "Scaled version of '{}' is not available".format(function.__name__)
            )

        return stub
    signature = inspect.signature(function)

    @functools.wraps(function)
    def rescaled_function(self, *args, **kwargs):
        params = signature.bind(self.base, *args, **kwargs)
        params.apply_defaults()
        arguments = params.arguments
        for k, power in scaling_info.kwargs.items():
            arguments[k] = rescale_value(arguments[k], self.scale, power)
        params = params.__class__(signature, arguments)
        results = function(*params.args, **params.kwargs)
        if not scaling_info.results:
            # do nothing
            return results
        wrapped_results = []
        is_tuple = isinstance(results, tuple)
        results = geoopt.utils.make_tuple(results)
        for i, (res, power) in enumerate(
            itertools.zip_longest(results, scaling_info.results, fillvalue=0)
        ):
            wrapped_results.append(rescale_value(res, self.scale, power))
        if not is_tuple:
            wrapped_results = wrapped_results[0]
        else:
            wrapped_results = results.__class__(wrapped_results)
        return wrapped_results

    return rescaled_function 
Example #24
Source File: __init__.py    From recruit with Apache License 2.0 5 votes vote down vote up
def bytes_to_str(b, encoding=None):
        return b.decode(encoding or 'utf-8')

    # The signature version below is directly copied from Django,
    # https://github.com/django/django/pull/4846 
Example #25
Source File: __init__.py    From yolo2-pytorch with GNU Lesser General Public License v3.0 5 votes vote down vote up
def parse_transform(config, method):
    if isinstance(method, str):
        attr = utils.parse_attr(method)
        sig = inspect.signature(attr)
        if len(sig.parameters) == 1:
            return attr(config)
        else:
            return attr()
    else:
        return method 
Example #26
Source File: test_overrides.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_inspect_sum(self):
        signature = inspect.signature(np.sum)
        assert_('axis' in signature.parameters) 
Example #27
Source File: __init__.py    From datasette with Apache License 2.0 5 votes vote down vote up
def _gather_arguments(fn, kwargs):
    parameters = inspect.signature(fn).parameters.keys()
    call_with = []
    for parameter in parameters:
        if parameter not in kwargs:
            raise TypeError(
                "{} requires parameters {}, missing: {}".format(
                    fn, tuple(parameters), set(parameters) - set(kwargs.keys())
                )
            )
        call_with.append(kwargs[parameter])
    return call_with 
Example #28
Source File: test_alter_axes.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_rename_signature(self):
        sig = inspect.signature(DataFrame.rename)
        parameters = set(sig.parameters)
        assert parameters == {"self", "mapper", "index", "columns", "axis",
                              "inplace", "copy", "level"} 
Example #29
Source File: util.py    From gated-graph-transformer-network with MIT License 5 votes vote down vote up
def get_compatible_kwargs(function, kwargs):
    kwargs = dict(kwargs)
    sig = inspect.signature(function)
    for param in sig.parameters.values():
        if param.name not in kwargs:
            if param.default is inspect.Parameter.empty:
                raise TypeError("kwargs missing required argument '{}'".format(param.name))
            else:
                kwargs[param.name] = param.default
    return kwargs 
Example #30
Source File: masterkey.py    From geofront with GNU Affero General Public License v3.0 5 votes vote down vote up
def generate_key(key_type: Type[PKey]=RSAKey,
                 bits: Optional[int]=None) -> PKey:
    """Generate a new key of the given ``key_type``.  If ``bits`` is omitted
    generate one with an appropriate bits.

    :param key_type: the type of a new master key.
                     it has to be a subclass of :class:`~paramiko.pkey.PKey`.
                     :class:`~paramiko.rsakey.RSAKey` by default.
                     (the default ``key_type`` can change in the future.)
    :type key_type: :class:`~typing.Type`\ [:class:`~paramiko.pkey.PKey`]
    :param bits: the number of bits the generated key should be.
                 if ``key_type`` is :class:`~paramiko.rsakey.RSAKey`
                 it has to be 512 at least.
                 the default value is :const:`None`, which means to
                 ``key_type``'s own default (appropriate) bits
    :return: a generate key which is an instance of the given ``key_type``
    :rtype: :class:`~paramiko.pkey.PKey`
    :raise KeyGenerationError: when it failed to generate a key using given
                               options (``key_type`` and ``bits``)

    .. versionadded:: 0.4.0

    """
    generate = key_type.generate
    bits_param = inspect.signature(generate).parameters['bits']
    if bits is None and bits_param.default is inspect.Signature.empty:
        new_key = generate(bits=1024)  # FIXME
    else:
        try:
            new_key = generate(bits=bits)
        except ValueError as e:
            raise KeyGenerationError(
                '{0.__name__}: {1!s}'.format(key_type, e)
            ) from e
    return new_key