当前位置: 首页>>代码示例>>Python>>正文


Python inspect.BoundArguments方法代码示例

本文整理汇总了Python中inspect.BoundArguments方法的典型用法代码示例。如果您正苦于以下问题:Python inspect.BoundArguments方法的具体用法?Python inspect.BoundArguments怎么用?Python inspect.BoundArguments使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在inspect的用法示例。


在下文中一共展示了inspect.BoundArguments方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _apply_guides

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import BoundArguments [as 别名]
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 
开发者ID:fwkz,项目名称:riposte,代码行数:25,代码来源:command.py

示例2: graph_function

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import BoundArguments [as 别名]
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 
开发者ID:openai,项目名称:lm-human-preferences,代码行数:28,代码来源:core.py

示例3: _bind_arguments

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import BoundArguments [as 别名]
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) 
开发者ID:fwkz,项目名称:riposte,代码行数:8,代码来源:command.py

示例4: gen_args

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import BoundArguments [as 别名]
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 
开发者ID:pschanely,项目名称:CrossHair,代码行数:39,代码来源:core.py

示例5: get_input_description

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import BoundArguments [as 别名]
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' 
开发者ID:pschanely,项目名称:CrossHair,代码行数:37,代码来源:core.py

示例6: _intermediate_argspec

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import BoundArguments [as 别名]
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) 
开发者ID:dry-python,项目名称:returns,代码行数:33,代码来源:curry.py

示例7: convert

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import BoundArguments [as 别名]
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 
开发者ID:bocadilloproject,项目名称:bocadillo,代码行数:40,代码来源:converters.py


注:本文中的inspect.BoundArguments方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。