Python inspect.BoundArguments() Examples

The following are 7 code examples of inspect.BoundArguments(). 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: command.py    From riposte with MIT License 6 votes vote down vote up
def _apply_guides(self, bound_arguments: inspect.BoundArguments) -> List:
        """ Apply guide functions.

        Apply guide functions to values of type `str` delivered by user
        using `input()`.

        Assumes that `args` have been already validated `_bind_arguments`,
        hence `args` is matching `_func` signature, (`args <= parameters`)

        """
        processed = []
        for name, value in bound_arguments.arguments.items():
            if (
                bound_arguments.signature.parameters[name].kind
                is inspect.Parameter.VAR_POSITIONAL
            ):
                arguments = self._process_arguments(name, *value)
            else:
                arguments = self._process_arguments(name, value)

            processed.extend(arguments)

        return processed 
Example #2
Source File: core.py    From lm-human-preferences with MIT License 5 votes vote down vote up
def graph_function(**schemas: Schema):
    def decorate(make_op):
        def make_ph(path, schema):
            return tf.placeholder(name=f'arg_{make_op.__name__}_{path}', shape=schema.shape, dtype=schema.dtype)
        phs = nest.map_structure_with_paths(make_ph, schemas)
        op = make_op(**phs)
        sig = inspect.signature(make_op)
        @wraps(make_op)
        def run(*args, **kwargs):
            bound: inspect.BoundArguments = sig.bind(*args, **kwargs)
            bound.apply_defaults()

            arg_dict = bound.arguments
            for name, param in sig.parameters.items():
                if param.kind == inspect.Parameter.VAR_KEYWORD:
                    kwargs = arg_dict[name]
                    arg_dict.update(kwargs)
                    del arg_dict[name]
            flat_phs = nest.flatten(phs)
            flat_arguments = nest.flatten_up_to(phs, bound.arguments)
            feed = {ph: arg for ph, arg in zip(flat_phs, flat_arguments)}
            run_options = tf.RunOptions(report_tensor_allocations_upon_oom=True)

            return tf.get_default_session().run(op, feed_dict=feed, options=run_options, run_metadata=None)
        return run
    return decorate 
Example #3
Source File: command.py    From riposte with MIT License 5 votes vote down vote up
def _bind_arguments(self, *args) -> inspect.BoundArguments:
        """ Check whether given `args` match `_func` signature. """
        try:
            return inspect.signature(self._func).bind(*args)
        except TypeError as e:
            raise CommandError(e) 
Example #4
Source File: core.py    From CrossHair with MIT License 5 votes vote down vote up
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 #5
Source File: core.py    From CrossHair with MIT License 5 votes vote down vote up
def get_input_description(statespace: StateSpace,
                          fn_name: str,
                          bound_args: inspect.BoundArguments,
                          return_val: object = _MISSING,
                          addl_context: str = '') -> str:
    debug('get_input_description: return_val: ', type(return_val))
    call_desc = ''
    if return_val is not _MISSING:
        try:
            repr_str = repr(return_val)
        except Exception as e:
            if isinstance(e, IgnoreAttempt):
                raise
            debug(f'Exception attempting to repr function output: {e}')
            repr_str = _UNABLE_TO_REPR
        if repr_str != 'None':
            call_desc = call_desc + ' (which returns ' + repr_str + ')'
    messages: List[str] = []
    for argname, argval in list(bound_args.arguments.items()):
        try:
            repr_str = repr(argval)
        except Exception as e:
            if isinstance(e, IgnoreAttempt):
                raise
            debug(f'Exception attempting to repr input "{argname}": {repr(e)}')
            repr_str = _UNABLE_TO_REPR
        messages.append(argname + ' = ' + repr_str)
    call_desc = fn_name + '(' + ', '.join(messages) + ')' + call_desc

    if addl_context:
        return addl_context + ' when calling ' + call_desc # ' and '.join(messages)
    elif messages:
        return 'when calling ' + call_desc # ' and '.join(messages)
    else:
        return 'for any input' 
Example #6
Source File: curry.py    From returns with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _intermediate_argspec(
    argspec: BoundArguments,
    args: tuple,
    kwargs: dict,
) -> _ArgSpec:
    """
    That's where ``curry`` magic happens.

    We use ``Signature`` objects from ``inspect`` to bind existing arguments.

    If there's a ``TypeError`` while we ``bind`` the arguments we try again.
    The second time we try to ``bind_partial`` arguments. It can fail too!
    It fails when there are invalid arguments
    or more arguments than we can fit in a function.

    This function is slow. Any optimization ideas are welcome!
    """
    full_args = argspec.args + args
    full_kwargs = {**argspec.kwargs, **kwargs}

    try:
        argspec.signature.bind(*full_args, **full_kwargs)
    except TypeError:
        # Another option is to copy-paste and patch `getcallargs` func
        # but in this case we get responsibility to maintain it over
        # python releases.
        # This place is also responsible for raising ``TypeError`` for cases:
        # 1. When incorrect argument is provided
        # 2. When too many arguments are provided
        return argspec.signature.bind_partial(*full_args, **full_kwargs), None
    return None, (full_args, full_kwargs) 
Example #7
Source File: converters.py    From bocadillo with MIT License 5 votes vote down vote up
def convert(self, args: tuple, kwargs: dict) -> typing.Tuple[tuple, dict]:
        bound: inspect.BoundArguments = self.signature.bind(*args, **kwargs)

        errors: typing.List[typesystem.ValidationError] = []

        for param_name, value in bound.arguments.items():
            try:
                annotation = self.annotations[param_name]
            except KeyError:
                continue

            # Find the TypeSystem field for the parameter's annotation.
            if isinstance(annotation, typesystem.Field):
                field = annotation
            else:
                try:
                    field = FIELD_ALIASES[annotation]()
                except KeyError:
                    continue

            # Perform validation.
            try:
                value = field.validate(value)
            except typesystem.ValidationError as exc:
                # NOTE: `add_prefix` sets the key of the error in the final
                # error's dict representation.
                errors.extend(exc.messages(add_prefix=param_name))
            else:
                bound.arguments[param_name] = value

        if errors:
            raise PathConversionError(messages=errors)

        # NOTE: apply defaults last to prevent validating the default values.
        # It's faster and less bug-prone.
        bound.apply_defaults()

        return bound.args, bound.kwargs