本文整理汇总了Python中inspect.Parameter.KEYWORD_ONLY属性的典型用法代码示例。如果您正苦于以下问题:Python Parameter.KEYWORD_ONLY属性的具体用法?Python Parameter.KEYWORD_ONLY怎么用?Python Parameter.KEYWORD_ONLY使用的例子?那么, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类inspect.Parameter
的用法示例。
在下文中一共展示了Parameter.KEYWORD_ONLY属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _yield_abbreviations_for_parameter
# 需要导入模块: from inspect import Parameter [as 别名]
# 或者: from inspect.Parameter import KEYWORD_ONLY [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 KEYWORD_ONLY [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: __init__
# 需要导入模块: from inspect import Parameter [as 别名]
# 或者: from inspect.Parameter import KEYWORD_ONLY [as 别名]
def __init__(self, f, local_dependencies=None, start_chiboard=True, default_logdir=""):
chi.set_loglevel('debug')
super().__init__(f)
self.start_chiboard = start_chiboard
self.f = f
self.local_dependencies = local_dependencies or []
self.should_stop = False
self.config = None
self.logdir = None
self.writers = {}
self.global_step = None
from inspect import Parameter
params = dict(daemon=Parameter('daemon',
Parameter.KEYWORD_ONLY,
default=False,
annotation="run in background"),
logdir=Parameter('logdir',
Parameter.KEYWORD_ONLY,
default=default_logdir))
# params.update(self.params)
self.params.update(params)
示例4: getargspec
# 需要导入模块: from inspect import Parameter [as 别名]
# 或者: from inspect.Parameter import KEYWORD_ONLY [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))
示例5: get_default_arg_names
# 需要导入模块: from inspect import Parameter [as 别名]
# 或者: from inspect.Parameter import KEYWORD_ONLY [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
)
示例6: get_default_arg_names
# 需要导入模块: from inspect import Parameter [as 别名]
# 或者: from inspect.Parameter import KEYWORD_ONLY [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: _convert_from_parameter_kind
# 需要导入模块: from inspect import Parameter [as 别名]
# 或者: from inspect.Parameter import KEYWORD_ONLY [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
示例8: _convert_to_parameter_kind
# 需要导入模块: from inspect import Parameter [as 别名]
# 或者: from inspect.Parameter import KEYWORD_ONLY [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
示例9: _validate_signature
# 需要导入模块: from inspect import Parameter [as 别名]
# 或者: from inspect.Parameter import KEYWORD_ONLY [as 别名]
def _validate_signature(func, *, keywords=None):
keywords = set(['bot'] + keywords)
from inspect import signature, Parameter
sig = signature(func)
missing_kw_only = []
for name in keywords:
param = sig.parameters.get(name, None)
if not param or param.kind != Parameter.KEYWORD_ONLY:
missing_kw_only.append(name)
if missing_kw_only:
raise SyntaxError('"{}: {}" missiong kwonly arg(s): {}'.format(func.__module__, func.__qualname__, ', '.join(missing_kw_only)))
示例10: _update_backend
# 需要导入模块: from inspect import Parameter [as 别名]
# 或者: from inspect.Parameter import KEYWORD_ONLY [as 别名]
def _update_backend(cls, backend):
if cls.__original_docstring__ is None:
cls.__original_docstring__ = cls.__doc__
all_keywords = set()
element_keywords = cls._element_keywords(backend)
for element, keywords in element_keywords.items():
with param.logging_level('CRITICAL'):
all_keywords |= set(keywords)
setattr(cls, element,
cls._create_builder(element, keywords))
filtered_keywords = [k for k in all_keywords if k not in cls._no_completion]
sorted_kw_set = sorted(set(filtered_keywords))
if sys.version_info.major == 2:
kws = ', '.join('{opt}=None'.format(opt=opt) for opt in sorted_kw_set)
old_doc = cls.__original_docstring__.replace(
'params(strict=Boolean, name=String)','')
cls.__doc__ = '\n opts({kws})'.format(kws=kws) + old_doc
else:
from inspect import Parameter, Signature
signature = Signature([Parameter('args', Parameter.VAR_POSITIONAL)]
+ [Parameter(kw, Parameter.KEYWORD_ONLY)
for kw in sorted_kw_set])
cls.__init__.__signature__ = signature
示例11: _generate_signature
# 需要导入模块: from inspect import Parameter [as 别名]
# 或者: from inspect.Parameter import KEYWORD_ONLY [as 别名]
def _generate_signature(cls):
from inspect import Signature, Parameter
keywords = ['backend', 'fig', 'holomap', 'widgets', 'fps', 'max_frames',
'size', 'dpi', 'filename', 'info', 'css', 'widget_location']
return Signature([Parameter(kw, Parameter.KEYWORD_ONLY) for kw in keywords])
示例12: _yield_abbreviations_for_parameter
# 需要导入模块: from inspect import Parameter [as 别名]
# 或者: from inspect.Parameter import KEYWORD_ONLY [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
示例13: _apply_signatures
# 需要导入模块: from inspect import Parameter [as 别名]
# 或者: from inspect.Parameter import KEYWORD_ONLY [as 别名]
def _apply_signatures(self):
from inspect import Parameter, Signature
from .viewable import Viewable
descendants = param.concrete_descendents(Viewable)
for cls in reversed(list(descendants.values())):
if cls.__doc__.startswith('params'):
prefix = cls.__doc__.split('\n')[0]
cls.__doc__ = cls.__doc__.replace(prefix, '')
sig = inspect.signature(cls.__init__)
sig_params = list(sig.parameters.values())
if not sig_params or sig_params[-1] != Parameter('params', Parameter.VAR_KEYWORD):
continue
parameters = sig_params[:-1]
processed_kws, keyword_groups = set(), []
for cls in reversed(cls.mro()):
keyword_group = []
for (k, v) in sorted(cls.__dict__.items()):
if (isinstance(v, param.Parameter) and k not in processed_kws
and not v.readonly):
keyword_group.append(k)
processed_kws.add(k)
keyword_groups.append(keyword_group)
parameters += [
Parameter(name, Parameter.KEYWORD_ONLY)
for kws in reversed(keyword_groups) for name in kws
if name not in sig.parameters
]
parameters.append(Parameter('kwargs', Parameter.VAR_KEYWORD))
cls.__init__.__signature__ = Signature(
parameters, return_annotation=sig.return_annotation
)
#---------------------------------------------------------------------
# Private API
#---------------------------------------------------------------------
示例14: partial_with_offset
# 需要导入模块: from inspect import Parameter [as 别名]
# 或者: from inspect.Parameter import KEYWORD_ONLY [as 别名]
def partial_with_offset(offset=1):
def bound_partial_with_offset(func, *partial_args, **partial_kwargs):
kwargs_partial = partial(func, **partial_kwargs)
@wraps(func)
def full_partial(*args, **kwargs):
full_args = args[:offset] + partial_args + args[offset:]
return kwargs_partial(*full_args, **kwargs)
# set correct signature of returned partial
# todo: pass arguments as keywords to partial, instead of this decorator?
# (where args are always the same)
func_sig = signature(full_partial)
parameter_names = tuple(func_sig.parameters)
partialed_positional_indices = []
for kwarg in partial_kwargs:
param = func_sig.parameters[kwarg]
if param.default is param.empty:
partialed_positional_indices.append(parameter_names.index(kwarg))
partial_params = list(func_sig.parameters.values())
for index in sorted(partialed_positional_indices, reverse=True):
# appending isn't needed for functionality, but more similar to partial
# and it shows that these arguments can still be updated as kwargs
partial_params.append(
partial_params[index].replace(
kind=Parameter.KEYWORD_ONLY,
default=partial_kwargs[partial_params[index].name],
)
)
del partial_params[index]
del partial_params[offset : offset + len(partial_args)]
full_partial.__signature__ = func_sig.replace(parameters=partial_params)
return full_partial
return bound_partial_with_offset
示例15: test_check_function_3
# 需要导入模块: from inspect import Parameter [as 别名]
# 或者: from inspect.Parameter import KEYWORD_ONLY [as 别名]
def test_check_function_3(state):
with pytest.raises(
InstructorError,
match=r"`check_function\(\)` couldn't match the first call of `round` to its signature:",
):
sig = Signature([Parameter("wrong", Parameter.KEYWORD_ONLY)])
state.check_function("round", 0, signature=sig)