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


Python inspect.Parameter方法代码示例

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


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

示例1: test_type_conv_invalid

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import Parameter [as 别名]
def test_type_conv_invalid(typ, value, multi):
    param = inspect.Parameter('foo', inspect.Parameter.POSITIONAL_ONLY)

    if multi:
        msg = 'foo: Invalid value {}'.format(value)
    elif typ is Enum:
        msg = ('foo: Invalid value {} - expected one of: foo, '
               'foo-bar'.format(value))
    else:
        msg = 'foo: Invalid {} value {}'.format(typ.__name__, value)

    with pytest.raises(cmdexc.ArgumentTypeError, match=msg):
        if multi:
            argparser.multitype_conv(param, [typ], value)
        else:
            argparser.type_conv(param, typ, value) 
开发者ID:qutebrowser,项目名称:qutebrowser,代码行数:18,代码来源:test_argparser.py

示例2: _check_func

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

示例3: _inspect_special_param

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import Parameter [as 别名]
def _inspect_special_param(self, param):
        """Check if the given parameter is a special one.

        Args:
            param: The inspect.Parameter to handle.

        Return:
            True if the parameter is special, False otherwise.
        """
        arg_info = self.get_arg_info(param)
        if arg_info.value is None:
            return False
        elif arg_info.value == usertypes.CommandValue.count:
            if param.default is inspect.Parameter.empty:
                raise TypeError("{}: handler has count parameter "
                                "without default!".format(self.name))
            return True
        elif isinstance(arg_info.value, usertypes.CommandValue):
            return True
        else:
            raise TypeError("{}: Invalid value={!r} for argument '{}'!"
                            .format(self.name, arg_info.value, param.name))
        raise utils.Unreachable 
开发者ID:qutebrowser,项目名称:qutebrowser,代码行数:25,代码来源:command.py

示例4: _get_type

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import Parameter [as 别名]
def _get_type(self, param):
        """Get the type of an argument from its default value or annotation.

        Args:
            param: The inspect.Parameter to look at.
        """
        arg_info = self.get_arg_info(param)
        if arg_info.value:
            # Filled values are passed 1:1
            return None
        elif param.kind in [inspect.Parameter.VAR_POSITIONAL,
                            inspect.Parameter.VAR_KEYWORD]:
            # For *args/**kwargs we only support strings
            assert param.annotation in [inspect.Parameter.empty, str], param
            return None
        elif param.annotation is not inspect.Parameter.empty:
            return param.annotation
        elif param.default not in [None, inspect.Parameter.empty]:
            return type(param.default)
        else:
            return str 
开发者ID:qutebrowser,项目名称:qutebrowser,代码行数:23,代码来源:command.py

示例5: _add_special_arg

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import Parameter [as 别名]
def _add_special_arg(self, *, value, param, args, kwargs):
        """Add a special argument value to a function call.

        Arguments:
            value: The value to add.
            param: The parameter being filled.
            args: The positional argument list. Gets modified directly.
            kwargs: The keyword argument dict. Gets modified directly.
        """
        if param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD:
            args.append(value)
        elif param.kind == inspect.Parameter.KEYWORD_ONLY:
            kwargs[param.name] = value
        else:
            raise TypeError("{}: invalid parameter type {} for argument "
                            "{!r}!".format(self.name, param.kind, param.name)) 
开发者ID:qutebrowser,项目名称:qutebrowser,代码行数:18,代码来源:command.py

示例6: callback

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

示例7: clean_params

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

示例8: _IsDefinableParameter

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import Parameter [as 别名]
def _IsDefinableParameter(parameter):
  """Checks if the parameter can be defined in `Params`.

  Args:
    parameter: inspect.Parameter to be checked.

  Returns:
    True if the `parameter`'s kind is either `POSITIONAL_OR_KEYWORD` or
    `KEYWORD_ONLY` which are definable in `Params`, False if it is either
    `VAR_POSITIONAL` or `VAR_KEYWORD` which are ignorable.

  Raises:
    ValueError: The `parameter` has another kind which are possibly not
      supported, e.g., `POSITIONAL_ONLY` parameters.
  """
  if parameter.kind in DEFINABLE_PARAMETER_KINDS:
    return True
  elif parameter.kind in IGNORABLE_PARAMETER_KINDS:
    return False
  else:
    raise ValueError('Unsupported parameter signature `%s` with kind `%s`.' %
                     (parameter.name, parameter.kind)) 
开发者ID:tensorflow,项目名称:lingvo,代码行数:24,代码来源:inspect_utils.py

示例9: _ExtractParameters

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import Parameter [as 别名]
def _ExtractParameters(func, ignore, bound):
  """Extracts parameters of func which can be defined in Params.

  Args:
    func: A callable to be analysed.
    ignore: A collection of parameter names in `func` to be ignored.
    bound: Whether the `func` is used as a bound function (an object method or a
      class method) or not. If True, the first parameter of the `func` will be
      ignored.

  Returns:
    A generator of `inspect.Parameter` representing definable parameters.
  """
  ignore = set(ignore if ignore is not None else ())

  # Obtains parameter signatures.
  parameters = tuple(inspect.signature(func).parameters.values())
  # Ignores the bound parameter: typically `self` or `cls`.
  parameters = parameters[(1 if bound else 0):]
  # Filters unnecessary parameters.
  parameters = filter(_IsDefinableParameter, parameters)
  parameters = (p for p in parameters if p.name not in ignore)

  return parameters 
开发者ID:tensorflow,项目名称:lingvo,代码行数:26,代码来源:inspect_utils.py

示例10: add_non_field_param_to_dependency

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import Parameter [as 别名]
def add_non_field_param_to_dependency(
    *, param: inspect.Parameter, dependant: Dependant
) -> Optional[bool]:
    if lenient_issubclass(param.annotation, Request):
        dependant.request_param_name = param.name
        return True
    elif lenient_issubclass(param.annotation, WebSocket):
        dependant.websocket_param_name = param.name
        return True
    elif lenient_issubclass(param.annotation, Response):
        dependant.response_param_name = param.name
        return True
    elif lenient_issubclass(param.annotation, BackgroundTasks):
        dependant.background_tasks_param_name = param.name
        return True
    elif lenient_issubclass(param.annotation, SecurityScopes):
        dependant.security_scopes_param_name = param.name
        return True
    return None 
开发者ID:tiangolo,项目名称:fastapi,代码行数:21,代码来源:utils.py

示例11: getdoc

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import Parameter [as 别名]
def getdoc(c_or_f: Union[Callable, type]) -> Optional[str]:
    if getattr(c_or_f, '__doc__', None) is None:
        return None
    doc = inspect.getdoc(c_or_f)
    if isinstance(c_or_f, type) and hasattr(c_or_f, '__init__'):
        sig = inspect.signature(c_or_f.__init__)
    else:
        sig = inspect.signature(c_or_f)

    def type_doc(name: str):
        param: inspect.Parameter = sig.parameters[name]
        cls = getattr(param.annotation, '__qualname__', repr(param.annotation))
        if param.default is not param.empty:
            return f'{cls}, optional (default: {param.default!r})'
        else:
            return cls

    return '\n'.join(
        f'{line} : {type_doc(line)}' if line.strip() in sig.parameters else line
        for line in doc.split('\n')
    ) 
开发者ID:theislab,项目名称:scanpy,代码行数:23,代码来源:_utils.py

示例12: test_get_defun_argspec_with_typed_non_eager_defun

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import Parameter [as 别名]
def test_get_defun_argspec_with_typed_non_eager_defun(self):
    # In a tf.function with a defined input signature, **kwargs or default
    # values are not allowed, but *args are, and the input signature may overlap
    # with *args.
    fn = tf.function(lambda x, y, *z: None, (
        tf.TensorSpec(None, tf.int32),
        tf.TensorSpec(None, tf.bool),
        tf.TensorSpec(None, tf.float32),
        tf.TensorSpec(None, tf.float32),
    ))
    self.assertEqual(
        collections.OrderedDict(function_utils.get_signature(fn).parameters),
        collections.OrderedDict(
            x=inspect.Parameter('x', inspect.Parameter.POSITIONAL_OR_KEYWORD),
            y=inspect.Parameter('y', inspect.Parameter.POSITIONAL_OR_KEYWORD),
            z=inspect.Parameter('z', inspect.Parameter.VAR_POSITIONAL),
        )) 
开发者ID:tensorflow,项目名称:federated,代码行数:19,代码来源:function_utils_test.py

示例13: test_get_signature_with_class_instance_method

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import Parameter [as 别名]
def test_get_signature_with_class_instance_method(self):

    class C:

      def __init__(self, x):
        self._x = x

      def foo(self, y):
        return self._x * y

    c = C(5)
    signature = function_utils.get_signature(c.foo)
    self.assertEqual(
        signature.parameters,
        collections.OrderedDict(
            y=inspect.Parameter('y', inspect.Parameter.POSITIONAL_OR_KEYWORD))) 
开发者ID:tensorflow,项目名称:federated,代码行数:18,代码来源:function_utils_test.py

示例14: takes_kwargs

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import Parameter [as 别名]
def takes_kwargs(obj) -> bool:
    """
    Checks whether a provided object takes in any positional arguments.
    Similar to takes_arg, we do this for both the __init__ function of
    the class or a function / method
    Otherwise, we raise an error
    """
    if inspect.isclass(obj):
        signature = inspect.signature(obj.__init__)
    elif inspect.ismethod(obj) or inspect.isfunction(obj):
        signature = inspect.signature(obj)
    else:
        raise ConfigurationError(f"object {obj} is not callable")
    return any(
        p.kind == inspect.Parameter.VAR_KEYWORD  # type: ignore
        for p in signature.parameters.values()
    ) 
开发者ID:allenai,项目名称:allennlp,代码行数:19,代码来源:from_params.py

示例15: test_signature_hashable

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


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