本文整理汇总了Python中collections.abc.Callable方法的典型用法代码示例。如果您正苦于以下问题:Python abc.Callable方法的具体用法?Python abc.Callable怎么用?Python abc.Callable使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类collections.abc
的用法示例。
在下文中一共展示了abc.Callable方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: assert_increases
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Callable [as 别名]
def assert_increases(self, delta: int, func: Callable, name=""):
""" shortcuts to verify func change is equal to delta """
test_case = self
class Detector:
def __init__(self):
self.previous = None
def __enter__(self):
self.previous = func()
def __exit__(self, exc_type, exc_val, exc_tb):
if not exc_val:
test_case.assertEqual(
self.previous + delta, func(), "{} should change {}".format(name, delta).strip()
)
return Detector()
示例2: __get_default
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Callable [as 别名]
def __get_default(self, item):
default_value = self._box_config['default_box_attr']
if default_value in (self.__class__, dict):
value = self.__class__(**self.__box_config())
elif isinstance(default_value, dict):
value = self.__class__(**self.__box_config(), **default_value)
elif isinstance(default_value, list):
value = box.BoxList(**self.__box_config())
elif isinstance(default_value, Callable):
value = default_value()
elif hasattr(default_value, 'copy'):
value = default_value.copy()
else:
value = default_value
self.__convert_and_store(item, value)
return value
示例3: test_Callable
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Callable [as 别名]
def test_Callable(self):
non_samples = [None, 42, 3.14, 1j,
"", b"", (), [], {}, set(),
(lambda: (yield))(),
(x for x in []),
]
for x in non_samples:
self.assertNotIsInstance(x, Callable)
self.assertFalse(issubclass(type(x), Callable), repr(type(x)))
samples = [lambda: None,
type, int, object,
len,
list.append, [].append,
]
for x in samples:
self.assertIsInstance(x, Callable)
self.assertTrue(issubclass(type(x), Callable), repr(type(x)))
self.validate_abstract_methods(Callable, '__call__')
self.validate_isinstance(Callable, '__call__')
示例4: __new__
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Callable [as 别名]
def __new__(cls, name, bases, namespace, _root=False,
args=None, result=None):
if args is None and result is None:
pass # Must be 'class Callable'.
else:
if args is not Ellipsis:
if not isinstance(args, list):
raise TypeError("Callable[args, result]: "
"args must be a list."
" Got %.100r." % (args,))
msg = "Callable[[arg, ...], result]: each arg must be a type."
args = tuple(_type_check(arg, msg) for arg in args)
msg = "Callable[args, result]: result must be a type."
result = _type_check(result, msg)
self = super().__new__(cls, name, bases, namespace, _root=_root)
self.__args__ = args
self.__result__ = result
return self
示例5: _get_check
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Callable [as 别名]
def _get_check(c):
if isinstance(c, bool):
return lambda e: c
elif isinstance(c, Callable):
return c
elif isinstance(c, (dict,)):
def check(event):
for k, v in six.iteritems(c):
if k in event:
if (isinstance(v, bool) and v) \
or (isinstance(v, Callable) and v(event[k])) \
or (isinstance(v, (six.text_type, six.binary_type))
and re_full_match(v, event[k])):
continue
return False
else:
if v is None:
continue
return False
return True
return check
示例6: __call__
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Callable [as 别名]
def __call__(self, entity):
entity = u(entity)
if isinstance(entity, (dict,)):
return any(c(entity) for c in self.check_list)
elif isinstance(entity, Callable):
fn = entity
@functools.wraps(fn)
def _wrapped(event, *args, **kwargs):
try:
if any(c(event) for c in self.check_list):
return self.call_processor(fn, event, *args, **kwargs)
except Exception as ex:
logger.error(
u'fail to call hooked function "{0}" with event "{1}", error: {2}'.format(fn, event, ex))
return event
return _wrapped
else:
errors = u"condition: unsupported data type: {0}".format(entity)
logger.error(errors)
raise SettingError(settings=errors)
示例7: _dict_transform_fn
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Callable [as 别名]
def _dict_transform_fn(tr):
def _real_transform(event):
result = {}
for k, v in six.iteritems(tr):
if isinstance(v, Callable):
v = v(event)
if isinstance(v, (six.text_type, six.binary_type)):
result[k] = v
elif v is None:
if k in result:
del result[k]
else:
logger.warning(u"unknown type of transform value for key:{0} value:{1}".format(k, v))
event.update(result)
return event
return _real_transform
示例8: _replace_arg
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Callable [as 别名]
def _replace_arg(arg, tvars, args):
"""An internal helper function: replace arg if it is a type variable
found in tvars with corresponding substitution from args or
with corresponding substitution sub-tree if arg is a generic type.
"""
if tvars is None:
tvars = []
if hasattr(arg, '_subs_tree') and isinstance(arg, (GenericMeta, _TypingBase)):
return arg._subs_tree(tvars, args)
if isinstance(arg, TypeVar):
for i, tvar in enumerate(tvars):
if arg == tvar:
return args[i]
return arg
# Special typing constructs Union, Optional, Generic, Callable and Tuple
# use three special attributes for internal bookkeeping of generic types:
# * __parameters__ is a tuple of unique free type parameters of a generic
# type, for example, Dict[T, T].__parameters__ == (T,);
# * __origin__ keeps a reference to a type that was subscripted,
# e.g., Union[T, int].__origin__ == Union;
# * __args__ is a tuple of all arguments used in subscripting,
# e.g., Dict[T, int].__args__ == (T, int).
示例9: __getitem__
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Callable [as 别名]
def __getitem__(self, parameters):
"""A thin wrapper around __getitem_inner__ to provide the latter
with hashable arguments to improve speed.
"""
if self.__origin__ is not None or self._gorg is not Callable:
return super().__getitem__(parameters)
if not isinstance(parameters, tuple) or len(parameters) != 2:
raise TypeError("Callable must be used as "
"Callable[[arg, ...], result].")
args, result = parameters
if args is Ellipsis:
parameters = (Ellipsis, result)
else:
if not isinstance(args, list):
raise TypeError("Callable[args, result]: args must be a list."
" Got %.100r." % (args,))
parameters = (tuple(args), result)
return self.__getitem_inner__(parameters)
示例10: check_callback
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Callable [as 别名]
def check_callback(callback):
"""
Check if callback is a callable or a list of callables.
"""
if callback is not None:
if isinstance(callback, Callable):
return [callback]
elif (isinstance(callback, list) and
all([isinstance(c, Callable) for c in callback])):
return callback
else:
raise ValueError("callback should be either a callable or "
"a list of callables.")
else:
return []
示例11: test_can_find_service_auth_criteria
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Callable [as 别名]
def test_can_find_service_auth_criteria(self):
# the auth criteria of the mocked service
auth_criteria = self.service().auth_criteria
# and it's the only one
assert len(auth_criteria) == 1, (
"There is an incorrect number of entries in the auth criteria map"
)
# check that the target service is in the dictionary
assert 'TestService' in auth_criteria, (
"Could not find service auth criteria in service dictionary"
)
# and that it's callable
assert isinstance(auth_criteria['TestService'], Callable), (
"Auth criteria handler was not callable."
)
示例12: auth_criteria
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Callable [as 别名]
def auth_criteria(self):
"""
This attribute provides the mapping of services to their auth requirement
Returns:
(dict) : the mapping from services to their auth requirements.
"""
# the dictionary we will return
auth = {}
# go over each attribute of the service
for attr in dir(self):
# make sure we could hit an infinite loop
if attr != 'auth_criteria':
# get the actual attribute
attribute = getattr(self, attr)
# if the service represents an auth criteria
if isinstance(attribute, Callable) and hasattr(attribute, '_service_auth'):
# add the criteria to the final results
auth[getattr(self, attr)._service_auth] = attribute
# return the auth mapping
return auth
示例13: test_extended_generic_rules_eq
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Callable [as 别名]
def test_extended_generic_rules_eq(self):
T = TypeVar('T')
U = TypeVar('U')
self.assertEqual(Tuple[T, T][int], Tuple[int, int])
self.assertEqual(typing.Iterable[Tuple[T, T]][T], typing.Iterable[Tuple[T, T]])
with self.assertRaises(TypeError):
Tuple[T, int][()]
with self.assertRaises(TypeError):
Tuple[T, U][T, ...]
self.assertEqual(Union[T, int][int], int)
self.assertEqual(Union[T, U][int, Union[int, str]], Union[int, str])
class Base: ...
class Derived(Base): ...
self.assertEqual(Union[T, Base][Derived], Base)
with self.assertRaises(TypeError):
Union[T, int][1]
self.assertEqual(Callable[[T], T][KT], Callable[[KT], KT])
self.assertEqual(Callable[..., List[T]][int], Callable[..., List[int]])
with self.assertRaises(TypeError):
Callable[[T], U][..., int]
with self.assertRaises(TypeError):
Callable[[T], U][[], int]
示例14: test_pickle
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Callable [as 别名]
def test_pickle(self):
global C # pickle wants to reference the class by name
T = TypeVar('T')
class B(Generic[T]):
pass
class C(B[int]):
pass
c = C()
c.foo = 42
c.bar = 'abc'
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
z = pickle.dumps(c, proto)
x = pickle.loads(z)
self.assertEqual(x.foo, 42)
self.assertEqual(x.bar, 'abc')
self.assertEqual(x.__dict__, {'foo': 42, 'bar': 'abc'})
simples = [Any, Union, Tuple, Callable, ClassVar, List, typing.Iterable]
for s in simples:
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
z = pickle.dumps(s, proto)
x = pickle.loads(z)
self.assertEqual(s, x)
示例15: test_success
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Callable [as 别名]
def test_success(input_post_view, decorator):
output_view = decorator(input_post_view)
assert isinstance(output_view, Callable)
wrapper_cls = _get_view_class(output_view)
assert wrapper_cls.get_serializer_class() == ExampleSerializer
assert isinstance(wrapper_cls.get_serializer(), ExampleSerializer)