當前位置: 首頁>>代碼示例>>Python>>正文


Python Parameter.POSITIONAL_OR_KEYWORD屬性代碼示例

本文整理匯總了Python中inspect.Parameter.POSITIONAL_OR_KEYWORD屬性的典型用法代碼示例。如果您正苦於以下問題:Python Parameter.POSITIONAL_OR_KEYWORD屬性的具體用法?Python Parameter.POSITIONAL_OR_KEYWORD怎麽用?Python Parameter.POSITIONAL_OR_KEYWORD使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在inspect.Parameter的用法示例。


在下文中一共展示了Parameter.POSITIONAL_OR_KEYWORD屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _yield_abbreviations_for_parameter

# 需要導入模塊: from inspect import Parameter [as 別名]
# 或者: from inspect.Parameter import POSITIONAL_OR_KEYWORD [as 別名]
def _yield_abbreviations_for_parameter(param, kwargs):
    """Get an abbreviation for a function parameter."""
    name = param.name
    kind = param.kind
    ann = param.annotation
    default = param.default
    not_found = (name, empty, empty)
    if kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY):
        if name in kwargs:
            value = kwargs.pop(name)
        elif ann is not empty:
            warn("Using function annotations to implicitly specify interactive controls is deprecated. Use an explicit keyword argument for the parameter instead.", DeprecationWarning)
            value = ann
        elif default is not empty:
            value = default
        else:
            yield not_found
        yield (name, value, default)
    elif kind == Parameter.VAR_KEYWORD:
        # In this case name=kwargs and we yield the items in kwargs with their keys.
        for k, v in kwargs.copy().items():
            kwargs.pop(k)
            yield k, v, empty 
開發者ID:luckystarufo,項目名稱:pySINDy,代碼行數:25,代碼來源:interaction.py

示例2: create_signature

# 需要導入模塊: from inspect import Parameter [as 別名]
# 或者: from inspect.Parameter import POSITIONAL_OR_KEYWORD [as 別名]
def create_signature(args, optional_args):
    """ Dynamically create a signature for a function from strings.

    This function can be used to create a signature for a dynamically
    generated function without generating a string representation of
    the function code and making an explicit eval call.

    Parameters
    ----------
    args : list
        List of strings that name the required arguments of a function.
    optional_args : list
        List of strings that name the optional arguments of a function.

    Returns
    -------
    Signature(p) : inspect.Signature instance
        A Signature object that can be used to validate arguments in
        a dynamically created function.
    """
    p = [Parameter(x, Parameter.POSITIONAL_OR_KEYWORD) for x in args]
    p += [Parameter(x, Parameter.KEYWORD_ONLY, default='DEFAULT')
          for x in optional_args]
    return Signature(p) 
開發者ID:civisanalytics,項目名稱:civis-python,代碼行數:26,代碼來源:_resources.py

示例3: getargspec

# 需要導入模塊: from inspect import Parameter [as 別名]
# 或者: from inspect.Parameter import POSITIONAL_OR_KEYWORD [as 別名]
def getargspec(func):
        signature = inspect.signature(func)

        args = []
        varargs = None
        keywords = None
        defaults = []

        for param in signature.parameters.values():  # type: Parameter
            if param.kind == Parameter.VAR_POSITIONAL:
                varargs = param.name
            elif param.kind in (
                    Parameter.POSITIONAL_ONLY,
                    Parameter.KEYWORD_ONLY,
                    Parameter.POSITIONAL_OR_KEYWORD):
                args.append(param.name)
            elif param.kind == Parameter.VAR_KEYWORD:
                keywords = param.name

            # noinspection PyProtectedMember
            if param.default is not inspect._empty:
                defaults.append(param.default)

        return ArgSpec(args, varargs, keywords, tuple(defaults)) 
開發者ID:Bahus,項目名稱:easy_cache,代碼行數:26,代碼來源:compat.py

示例4: get_default_arg_names

# 需要導入模塊: from inspect import Parameter [as 別名]
# 或者: from inspect.Parameter import POSITIONAL_OR_KEYWORD [as 別名]
def get_default_arg_names(function):
    # Note: this code intentionally mirrors the code at the beginning of getfuncargnames,
    # to get the arguments which were excluded from its result because they had default values
    return tuple(
        p.name
        for p in signature(function).parameters.values()
        if p.kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY)
        and p.default is not Parameter.empty
    ) 
開發者ID:sofia-netsurv,項目名稱:python-netsurv,代碼行數:11,代碼來源:compat.py

示例5: positional_arguments

# 需要導入模塊: from inspect import Parameter [as 別名]
# 或者: from inspect.Parameter import POSITIONAL_OR_KEYWORD [as 別名]
def positional_arguments(sig):
    return len([p for n, p in sig.parameters.items()
                if p.kind in (Parameter.POSITIONAL_ONLY,
                              Parameter.POSITIONAL_OR_KEYWORD)]) 
開發者ID:kaste,項目名稱:mockito-python,代碼行數:6,代碼來源:signature.py

示例6: get_default_arg_names

# 需要導入模塊: from inspect import Parameter [as 別名]
# 或者: from inspect.Parameter import POSITIONAL_OR_KEYWORD [as 別名]
def get_default_arg_names(function: Callable[..., Any]) -> Tuple[str, ...]:
    # Note: this code intentionally mirrors the code at the beginning of getfuncargnames,
    # to get the arguments which were excluded from its result because they had default values
    return tuple(
        p.name
        for p in signature(function).parameters.values()
        if p.kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY)
        and p.default is not Parameter.empty
    ) 
開發者ID:pytest-dev,項目名稱:pytest,代碼行數:11,代碼來源:compat.py

示例7: __init__

# 需要導入模塊: from inspect import Parameter [as 別名]
# 或者: from inspect.Parameter import POSITIONAL_OR_KEYWORD [as 別名]
def __init__(self, name, default=Parameter.empty, annotation=Parameter.empty):
        super().__init__(name, Parameter.POSITIONAL_OR_KEYWORD, default=default, annotation=annotation) 
開發者ID:kubeflow,項目名稱:pipelines,代碼行數:4,代碼來源:_dynamic.py

示例8: dict_command

# 需要導入模塊: from inspect import Parameter [as 別名]
# 或者: from inspect.Parameter import POSITIONAL_OR_KEYWORD [as 別名]
def dict_command(**spec):

    def wrap(command_func):

        expected = expand_spec(spec.get("expected", {}))
        optional = expand_spec(spec.get("optional", {}))

        @wraps(command_func)
        async def wrapped_command(ctx, *args, **details):
            # Find the last positional. That is where the dict_args will be passed.
            args_spec = inspect.signature(command_func)
            params = list(args_spec.parameters.values())
            args_dict_param = next((param for param in reversed(params)
                                    if param.kind is Parameter.POSITIONAL_OR_KEYWORD))

            # Get all args after and including the position of the arg for the dict_args
            # Those will be processed into a dict.
            arg_dict_index = params.index(args_dict_param) - 1  # -1 to ignore ctx arg
            dict_args = determine_dict_args(list(args[arg_dict_index:]), wrapped_command, ctx,
                                            expected=expected, optional=optional)

            if dict_args is False:
                # Invalid
                await util.get_client(ctx.server.id).add_reaction(ctx, emojis.QUESTION_REACT)
            else:
                # Run command.
                kwargs = details
                kwargs[args_dict_param.name] = dict_args
                await command_func(ctx, *args[:arg_dict_index], **kwargs)

        return wrapped_command

    return wrap 
開發者ID:MacDue,項目名稱:DueUtil,代碼行數:35,代碼來源:commandextras.py

示例9: _convert_from_parameter_kind

# 需要導入模塊: from inspect import Parameter [as 別名]
# 或者: from inspect.Parameter import POSITIONAL_OR_KEYWORD [as 別名]
def _convert_from_parameter_kind(kind):
    if kind == Parameter.POSITIONAL_ONLY:
        return 0
    if kind == Parameter.POSITIONAL_OR_KEYWORD:
        return 1
    if kind == Parameter.VAR_POSITIONAL:
        return 2
    if kind == Parameter.KEYWORD_ONLY:
        return 3
    if kind == Parameter.VAR_KEYWORD:
        return 4 
開發者ID:ray-project,項目名稱:ray,代碼行數:13,代碼來源:signature.py

示例10: _convert_to_parameter_kind

# 需要導入模塊: from inspect import Parameter [as 別名]
# 或者: from inspect.Parameter import POSITIONAL_OR_KEYWORD [as 別名]
def _convert_to_parameter_kind(value):
    if value == 0:
        return Parameter.POSITIONAL_ONLY
    if value == 1:
        return Parameter.POSITIONAL_OR_KEYWORD
    if value == 2:
        return Parameter.VAR_POSITIONAL
    if value == 3:
        return Parameter.KEYWORD_ONLY
    if value == 4:
        return Parameter.VAR_KEYWORD 
開發者ID:ray-project,項目名稱:ray,代碼行數:13,代碼來源:signature.py

示例11: __init__

# 需要導入模塊: from inspect import Parameter [as 別名]
# 或者: from inspect.Parameter import POSITIONAL_OR_KEYWORD [as 別名]
def __init__(self, typename, fields):
        if not isinstance(typename, str):
            raise TypeError(f"type name must be string, not {type(typename)}")

        if isinstance(fields, str):
            spaces = any([whitespace in fields for whitespace in string.whitespace])
            commas = "," in fields
            if spaces and commas:
                raise ValueError(f"Single string fields={fields} cannot have both spaces and commas.")
            elif spaces:
                fields = fields.split()
            elif commas:
                fields = fields.split(",")
            else:
                # If there are neither spaces nor commas, then there is only one field.
                fields = (fields,)
        fields = tuple(fields)

        for field in fields:
            if not isinstance(field, str):
                raise ValueError(f"field names must be strings: {field}")
            if field.startswith("_"):
                raise ValueError(f"field names cannot start with an "
                                 f"underscore: {field}")
            if field in ("index", "count"):
                raise ValueError(f"can't name field 'index' or 'count'")
        self.__dict__["_typename"] = typename
        self.__dict__["_fields"] = fields
        self.__dict__["_signature"] = Sig(Param(field,
            Param.POSITIONAL_OR_KEYWORD) for field in fields) 
開發者ID:astooke,項目名稱:rlpyt,代碼行數:32,代碼來源:collections.py

示例12: test_pane_signature

# 需要導入模塊: from inspect import Parameter [as 別名]
# 或者: from inspect.Parameter import POSITIONAL_OR_KEYWORD [as 別名]
def test_pane_signature(pane):
    from inspect import Parameter, signature
    parameters = signature(pane).parameters
    assert len(parameters) == 2
    assert 'object' in parameters
    assert parameters['object'] == Parameter('object', Parameter.POSITIONAL_OR_KEYWORD, default=None) 
開發者ID:holoviz,項目名稱:panel,代碼行數:8,代碼來源:test_base.py

示例13: _yield_abbreviations_for_parameter

# 需要導入模塊: from inspect import Parameter [as 別名]
# 或者: from inspect.Parameter import POSITIONAL_OR_KEYWORD [as 別名]
def _yield_abbreviations_for_parameter(parameter, kwargs):
    """Get an abbreviation for a function parameter."""
    name = parameter.name
    kind = parameter.kind
    ann = parameter.annotation
    default = parameter.default
    not_found = (name, empty, empty)
    if kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY):
        if name in kwargs:
            value = kwargs.pop(name)
        elif ann is not empty:
            param.main.warning("Using function annotations to implicitly specify interactive controls is deprecated. "
                               "Use an explicit keyword argument for the parameter instead.", DeprecationWarning)
            value = ann
        elif default is not empty:
            value = default
            if isinstance(value, (Iterable, Mapping)):
                value = fixed(value)
        else:
            yield not_found
        yield (name, value, default)
    elif kind == Parameter.VAR_KEYWORD:
        # In this case name=kwargs and we yield the items in kwargs with their keys.
        for k, v in kwargs.copy().items():
            kwargs.pop(k)
            yield k, v, empty 
開發者ID:holoviz,項目名稱:panel,代碼行數:28,代碼來源:interact.py

示例14: parse_args_and_run

# 需要導入模塊: from inspect import Parameter [as 別名]
# 或者: from inspect.Parameter import POSITIONAL_OR_KEYWORD [as 別名]
def parse_args_and_run(self, args=None):
    args = args or sys.argv
    import argparse
    parser = argparse.ArgumentParser(description=self.f.__name__)

    for n, p in self.params.items():
      d = p.default == Parameter.empty
      t = str if d else type(p.default)
      if t is bool:
        g = parser.add_mutually_exclusive_group(required=False)
        g.add_argument('--' + n, dest=n, action='store_true')
        g.add_argument('--no-' + n, dest=n, action='store_false')
        parser.set_defaults(**{n: Parameter.empty})
      elif p.kind == Parameter.POSITIONAL_OR_KEYWORD:
        g = parser.add_mutually_exclusive_group(required=d)
        g.add_argument(n, nargs='?', type=t, default=Parameter.empty)
        g.add_argument('--' + n, dest='--' + n, type=t, default=Parameter.empty, help=argparse.SUPPRESS)
      elif p.kind == Parameter.KEYWORD_ONLY:
        parser.add_argument('--' + n, type=type(p.default), default=p.default)

    ag = vars(parser.parse_args())
    parsed = {}
    for n, p in self.params.items():
      a, b, c = ag[n], ag.get('--' + n, Parameter.empty), p.default
      v = a if a != Parameter.empty else b if b != Parameter.empty else c
      parsed.update({n: v})

    result = self.run(**parsed)

    from chi.logger import logger
    logger.info('Finishing with ' + str(result))

    sys.exit(result) 
開發者ID:rmst,項目名稱:chi,代碼行數:35,代碼來源:app.py

示例15: getfuncargnames

# 需要導入模塊: from inspect import Parameter [as 別名]
# 或者: from inspect.Parameter import POSITIONAL_OR_KEYWORD [as 別名]
def getfuncargnames(function, is_method=False, cls=None):
    """Returns the names of a function's mandatory arguments.

    This should return the names of all function arguments that:
        * Aren't bound to an instance or type as in instance or class methods.
        * Don't have default values.
        * Aren't bound with functools.partial.
        * Aren't replaced with mocks.

    The is_method and cls arguments indicate that the function should
    be treated as a bound method even though it's not unless, only in
    the case of cls, the function is a static method.

    @RonnyPfannschmidt: This function should be refactored when we
    revisit fixtures. The fixture mechanism should ask the node for
    the fixture names, and not try to obtain directly from the
    function object well after collection has occurred.

    """
    # The parameters attribute of a Signature object contains an
    # ordered mapping of parameter names to Parameter instances.  This
    # creates a tuple of the names of the parameters that don't have
    # defaults.
    try:
        parameters = signature(function).parameters
    except (ValueError, TypeError) as e:
        fail(
            "Could not determine arguments of {!r}: {}".format(function, e),
            pytrace=False,
        )

    arg_names = tuple(
        p.name
        for p in parameters.values()
        if (
            p.kind is Parameter.POSITIONAL_OR_KEYWORD
            or p.kind is Parameter.KEYWORD_ONLY
        )
        and p.default is Parameter.empty
    )
    # If this function should be treated as a bound method even though
    # it's passed as an unbound method or function, remove the first
    # parameter name.
    if is_method or (
        cls and not isinstance(cls.__dict__.get(function.__name__, None), staticmethod)
    ):
        arg_names = arg_names[1:]
    # Remove any names that will be replaced with mocks.
    if hasattr(function, "__wrapped__"):
        arg_names = arg_names[num_mock_patch_args(function) :]
    return arg_names 
開發者ID:sofia-netsurv,項目名稱:python-netsurv,代碼行數:53,代碼來源:compat.py


注:本文中的inspect.Parameter.POSITIONAL_OR_KEYWORD屬性示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。