本文整理汇总了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
示例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)
示例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))
示例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
)
示例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)])
示例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
)
示例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)
示例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
示例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
示例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
示例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)
示例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)
示例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
示例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)
示例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