本文整理汇总了Python中inspect._empty方法的典型用法代码示例。如果您正苦于以下问题:Python inspect._empty方法的具体用法?Python inspect._empty怎么用?Python inspect._empty使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类inspect
的用法示例。
在下文中一共展示了inspect._empty方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_config
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import _empty [as 别名]
def create_config(klass, config, msg):
try:
return klass(**config)
except TypeError:
# Inspect the GlobalConfig constructor to find which
# parameters are required and don't have a default
# value.
required_args = {
name
for name, param in inspect.signature(klass.__init__).parameters.items()
if param.default == inspect._empty
and name not in {'self', 'kwargs'}
}
missing_args = required_args - config.keys()
missing = ', '.join(
"'{arg}'".format(arg=arg)
for arg in sorted(missing_args)
)
raise BriefcaseConfigError(
"{msg} is incomplete (missing {missing})".format(
msg=msg,
missing=missing
)
)
示例2: adapt_arg
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import _empty [as 别名]
def adapt_arg(arg, ann, deserializers=DESERIALIZERS):
if not ann or ann is inspect._empty:
return arg
if ann.__module__ == "typing":
if typing.Iterable in ann.__mro__:
return adapt_iterable(arg, ann, deserializers)
elif typing.Tuple in ann.__mro__:
return adapt_tuple(arg, ann, deserializers)
if isinstance(arg, ann):
return arg
deserializer = get_deserializer(ann, deserializers)
if deserializer:
adapted = deserializer(arg, ann)
if adapted:
return adapted
return arg
示例3: move_args_to_kwargs
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import _empty [as 别名]
def move_args_to_kwargs(original_function, args, kwargs):
args = list(args)
import inspect
signature = inspect.signature(original_function)
i = 0
for name, parameter in signature.parameters.items():
if i >= len(args):
break
if parameter.default is not inspect._empty:
value = args.pop(i)
kwargs[name] = value
else:
i += 1
return args, kwargs
示例4: __str__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import _empty [as 别名]
def __str__(self):
"""wrap defaults"""
kind = self.kind
formatted = self._name
# Fill in defaults
if (
self._default is not inspect._empty
or kind == inspect._KEYWORD_ONLY
):
formatted = '{}={}'.format(formatted, formatted)
if kind == inspect._VAR_POSITIONAL:
formatted = '*' + formatted
elif kind == inspect._VAR_KEYWORD:
formatted = '**' + formatted
return formatted
示例5: test_load_methods
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import _empty [as 别名]
def test_load_methods():
for dataset in DATASETS:
dataset_name = dataset.__name__.split('.')[1]
all_methods = dir(dataset)
load_methods = [
getattr(dataset, m) for m in all_methods if m.startswith('load_')
]
for load_method in load_methods:
method_name = load_method.__name__
params = [
p
for p in signature(load_method).parameters.values()
if p.default == inspect._empty
] # get list of parameters that don't have defaults
# add to the EXCEPTIONS dictionary above if your load_* function needs
# more than one argument.
if dataset_name in EXCEPTIONS and method_name in EXCEPTIONS[dataset_name]:
extra_params = EXCEPTIONS[dataset_name][method_name]
with pytest.raises(IOError):
load_method("a/fake/filepath", **extra_params)
else:
with pytest.raises(IOError):
load_method("a/fake/filepath")
示例6: is_passed_kwargs_compatible_with_passed_function
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import _empty [as 别名]
def is_passed_kwargs_compatible_with_passed_function(self, kwargs):
params_inspection = inspect.signature(self.passed_function).parameters
for param in params_inspection:
has_default = True if params_inspection[param].default is not inspect._empty else False
if not has_default and param not in kwargs.keys():
raise ConfigError("`%s` was passed to filter_data. All its arguments without defaults must "
"also be passed, but `%s` was not. Do so with \"%s = ...\"" \
% (self.passed_function, param, param))
else:
self.append_info_log("`%s` of `%s` was passed or has default" % (param, self.passed_function), True)
bad_args = [arg for arg in kwargs.keys() if arg not in params_inspection]
if bad_args:
raise ConfigError("VariabilityFilter :: The args [%s] were passed to filter_data,\
but are not args of `%s`. Available args for this function are [%s]" \
% (", ".join(bad_args), self.passed_function, ", ".join(params_inspection)))
for kwarg in kwargs:
self.append_info_log("filter argument: `%s`" % (kwarg), "valid argument for `%s`" % (self.passed_function))
示例7: __init__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import _empty [as 别名]
def __init__(self):
self.signal = None
self.indices = None
self.methods = METHODS
self.method_names = [method.__name__ for method in METHODS]
self.params = {
method.__name__: OrderedDict(
[
(p.name, p.default)
for p in inspect.signature(method).parameters.values()
if p.default is not inspect._empty
]
)
for method in METHODS
}
self._method = self.method_names[0]
示例8: check
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import _empty [as 别名]
def check(self) -> None:
"""
Check for docstring and arguments have default values set.
Raises exception if function definition does not contain docstring or default values.
:return: None
"""
if not self.doc:
raise ValueError("Function docstring is missing")
if super()._arguments[0].name != self.CONTROL_ARG_NAME:
raise ValueError(
f"first function argument must be named `{self.CONTROL_ARG_NAME}`!"
)
for arg in self._arguments:
if arg.default == inspect._empty: # type: ignore # pylint: disable=protected-access
raise ValueError(
"function should have default values for every param except first one"
)
示例9: sig_map
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import _empty [as 别名]
def sig_map(ver):
'''
Generates the map dict for the signature verification
'''
vsig = inspect.signature(ver)
vparams = list(vsig.parameters.values())
vdat = {'args': [], 'v_pos': -1, 'kw': [], 'kwargs': False, 'ann': {}}
for ind in range(len(vparams)):
param = vparams[ind]
val = param.kind.value
name = param.name
if val == 0 or val == 1:
vdat['args'].append(name)
if param.default != inspect._empty: # Is a KW, can be inside of **kwargs
vdat['kw'].append(name)
elif val == 2:
vdat['v_pos'] = ind
elif val == 3:
vdat['kw'].append(name)
elif val == 4:
vdat['kwargs'] = ind
if param.annotation != inspect._empty:
vdat['ann'][name] = param.annotation
return vdat
示例10: __new__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import _empty [as 别名]
def __new__(mcs, name, bases, namespace, **kwargs):
class_obj = super().__new__(mcs, name, bases, dict(namespace))
all_args, all_kwargs = [], {}
signature_parameters = signature(class_obj.__init__).parameters
for k, v in signature_parameters.items():
if k not in ["self", "args", "kwargs"]: # FLAG: Might need kwargs to ok "input_dim"
if (v.kind in [v.KEYWORD_ONLY, v.POSITIONAL_OR_KEYWORD]) and v.default != _empty:
all_kwargs[k] = v.default
else:
all_args.append(k)
setattr(class_obj, "__hh_default_args", all_args)
setattr(class_obj, "__hh_default_kwargs", all_kwargs)
return class_obj
示例11: validate
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import _empty [as 别名]
def validate(cls):
if cls.__validated__:
return
cls.__validated__ = True
for _, field in cls.__fields__.items():
if not isinstance(field, (Field, ResolverField)):
raise ValidationError(f'{field} is an invalid field type')
if field.ftype == _empty:
raise ValidationError(f'The return type of resolver "{cls.__name__}.{field.name}" must not be empty')
print_type(field.ftype, except_types=(types.InputType))
if isinstance(field, ResolverField):
for gtype in field.params.values():
print_type(gtype)
shelled = shelling_type(gtype)
if isinstance(shelled, types.InputType):
shelled.validate()
if isinstance(field.ftype, ObjectType):
field.ftype.validate()
if is_union(field.ftype):
shelled = shelling_type(field.ftype)
if isinstance(shelled, ObjectType):
shelled.validate()
示例12: _indicator_table
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import _empty [as 别名]
def _indicator_table(realm):
"""Return a sequence of dicts storing metadata about all available indices."""
import inspect
inds = _get_indicators(getattr(xclim, realm))
table = {}
for indname, ind in inds.items():
# Apply default values
args = {
name: p.default if p.default != inspect._empty else f"<{name}>"
for (name, p) in ind._sig.parameters.items()
}
try:
table[indname] = ind.json(args)
except KeyError as err:
print(f"{ind.identifier} could not be documented.({err})")
else:
table[indname]["function"] = f"xclim.indices.{ind.compute.__name__}"
return table
示例13: _apply_defaults
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import _empty [as 别名]
def _apply_defaults(bound_arguments):
"""
Set default values for missing arguments. (from Python3.5)
"""
from collections import OrderedDict
from inspect import _empty, _VAR_POSITIONAL, _VAR_KEYWORD
arguments = bound_arguments.arguments
new_arguments = []
for name, param in bound_arguments._signature.parameters.items():
try:
new_arguments.append((name, arguments[name]))
except KeyError:
if param.default is not _empty:
val = param.default
elif param.kind is _VAR_POSITIONAL:
val = ()
elif param.kind is _VAR_KEYWORD:
val = {}
else:
# This BoundArguments was likely produced by
# Signature.bind_partial().
continue
new_arguments.append((name, val))
bound_arguments.arguments = OrderedDict(new_arguments)
示例14: getargspec
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import _empty [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))
示例15: typecasted
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import _empty [as 别名]
def typecasted(func):
"""Decorator that converts arguments via annotations."""
signature = inspect.signature(func).parameters.items()
@wraps(func)
def wrapper(*args, **kwargs):
args = list(args)
new_args = []
new_kwargs = {}
for _, param in signature:
converter = param.annotation
if converter is inspect._empty:
converter = lambda a: a # do nothing
if param.kind is param.POSITIONAL_OR_KEYWORD:
if args:
to_conv = args.pop(0)
new_args.append(converter(to_conv))
elif param.kind is param.VAR_POSITIONAL:
for a in args:
new_args.append(converter(a))
else:
for k, v in kwargs.items():
nk, nv = converter(k, v)
new_kwargs[nk] = nv
return func(*new_args, **new_kwargs)
return wrapper