當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。