本文整理汇总了Python中functools.singledispatch方法的典型用法代码示例。如果您正苦于以下问题:Python functools.singledispatch方法的具体用法?Python functools.singledispatch怎么用?Python functools.singledispatch使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类functools
的用法示例。
在下文中一共展示了functools.singledispatch方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: convert_yielded
# 需要导入模块: import functools [as 别名]
# 或者: from functools import singledispatch [as 别名]
def convert_yielded(yielded):
"""Convert a yielded object into a `.Future`.
The default implementation accepts lists, dictionaries, and Futures.
If the `~functools.singledispatch` library is available, this function
may be extended to support additional types. For example::
@convert_yielded.register(asyncio.Future)
def _(asyncio_future):
return tornado.platform.asyncio.to_tornado_future(asyncio_future)
.. versionadded:: 4.1
"""
# Lists and dicts containing YieldPoints were handled earlier.
if isinstance(yielded, (list, dict)):
return multi(yielded)
elif is_future(yielded):
return yielded
elif isawaitable(yielded):
return _wrap_awaitable(yielded)
else:
raise BadYieldError("yielded unknown object %r" % (yielded,))
示例2: applicationpolicy
# 需要导入模块: import functools [as 别名]
# 或者: from functools import singledispatch [as 别名]
def applicationpolicy(arg: Callable) -> Callable:
"""
Decorator for application policy method.
Allows policy to be built up from methods
registered for different event classes.
"""
assert isfunction(arg), arg
@no_type_check
def _mutator(func):
wrapped = singledispatch(func)
@wraps(wrapped)
def wrapper(*args, **kwargs):
event = kwargs.get("event") or args[-1]
return wrapped.dispatch(type(event))(*args, **kwargs)
wrapper.register = wrapped.register
return wrapper
return _mutator(arg)
示例3: encoderpolicy
# 需要导入模块: import functools [as 别名]
# 或者: from functools import singledispatch [as 别名]
def encoderpolicy(arg=None):
"""
Decorator for encoder policy.
Allows default behaviour to be built up from methods
registered for different types of things, rather than
chain of isinstance() calls in a long if-else block.
"""
def _mutator(func):
wrapped = singledispatch(func)
@wraps(wrapped)
def wrapper(*args, **kwargs):
obj = kwargs.get("obj") or args[-1]
return wrapped.dispatch(type(obj))(*args, **kwargs)
wrapper.register = wrapped.register
return wrapper
assert isfunction(arg), arg
return _mutator(arg)
示例4: to_dict
# 需要导入模块: import functools [as 别名]
# 或者: from functools import singledispatch [as 别名]
def to_dict(obj, **kwargs):
"""
Convert an object into dictionary. Uses singledispatch to allow for
clean extensions for custom class types.
Reference: https://pypi.python.org/pypi/singledispatch
:param obj: object instance
:param kwargs: keyword arguments such as suppress_private_attr,
suppress_empty_values, dict_factory
:return: converted dictionary.
"""
# if is_related, then iterate attrs.
if is_model(obj.__class__):
return related_obj_to_dict(obj, **kwargs)
# else, return obj directly. register a custom to_dict if you need to!
# reference: https://pypi.python.org/pypi/singledispatch
else:
return obj
示例5: test_mro
# 需要导入模块: import functools [as 别名]
# 或者: from functools import singledispatch [as 别名]
def test_mro(self):
@functools.singledispatch
def g(obj):
return "base"
class A:
pass
class C(A):
pass
class B(A):
pass
class D(C, B):
pass
def g_A(a):
return "A"
def g_B(b):
return "B"
g.register(A, g_A)
g.register(B, g_B)
self.assertEqual(g(A()), "A")
self.assertEqual(g(B()), "B")
self.assertEqual(g(C()), "A")
self.assertEqual(g(D()), "B")
示例6: test_c_classes
# 需要导入模块: import functools [as 别名]
# 或者: from functools import singledispatch [as 别名]
def test_c_classes(self):
@functools.singledispatch
def g(obj):
return "base"
@g.register(decimal.DecimalException)
def _(obj):
return obj.args
subn = decimal.Subnormal("Exponent < Emin")
rnd = decimal.Rounded("Number got rounded")
self.assertEqual(g(subn), ("Exponent < Emin",))
self.assertEqual(g(rnd), ("Number got rounded",))
@g.register(decimal.Subnormal)
def _(obj):
return "Too small to care."
self.assertEqual(g(subn), "Too small to care.")
self.assertEqual(g(rnd), ("Number got rounded",))
示例7: import_single_dispatch
# 需要导入模块: import functools [as 别名]
# 或者: from functools import singledispatch [as 别名]
def import_single_dispatch():
try:
from functools import singledispatch
except ImportError:
singledispatch = None
if not singledispatch:
try:
from singledispatch import singledispatch
except ImportError:
pass
if not singledispatch:
raise Exception(
"It seems your python version does not include "
"functools.singledispatch. Please install the 'singledispatch' "
"package. More information here: "
"https://pypi.python.org/pypi/singledispatch"
)
return singledispatch
# noqa
示例8: convert_yielded
# 需要导入模块: import functools [as 别名]
# 或者: from functools import singledispatch [as 别名]
def convert_yielded(yielded):
"""Convert a yielded object into a `.Future`.
The default implementation accepts lists, dictionaries, and Futures.
If the `~functools.singledispatch` library is available, this function
may be extended to support additional types. For example::
@convert_yielded.register(asyncio.Future)
def _(asyncio_future):
return tornado.platform.asyncio.to_tornado_future(asyncio_future)
.. versionadded:: 4.1
"""
# Lists and dicts containing YieldPoints were handled earlier.
if yielded is None:
return moment
elif isinstance(yielded, (list, dict)):
return multi(yielded)
elif is_future(yielded):
return yielded
elif isawaitable(yielded):
return _wrap_awaitable(yielded)
else:
raise BadYieldError("yielded unknown object %r" % (yielded,))
示例9: import_single_dispatch
# 需要导入模块: import functools [as 别名]
# 或者: from functools import singledispatch [as 别名]
def import_single_dispatch():
try:
from functools import singledispatch
except ImportError:
singledispatch = None
if not singledispatch:
try:
from singledispatch import singledispatch
except ImportError:
pass
if not singledispatch:
raise Exception(
"It seems your python version does not include "
"functools.singledispatch. Please install the 'singledispatch' "
"package. More information here: "
"https://pypi.python.org/pypi/singledispatch"
)
return singledispatch
示例10: methdispatch
# 需要导入模块: import functools [as 别名]
# 或者: from functools import singledispatch [as 别名]
def methdispatch(func):
"""
A decorator that is used to support singledispatch style functionality
for instance methods. By default, singledispatch selects a function to
call from registered based on the type of args[0]:
def wrapper(*args, **kw):
return dispatch(args[0].__class__)(*args, **kw)
This uses singledispatch to do achieve this but instead uses args[1]
since args[0] will always be self.
"""
dispatcher = singledispatch(func)
def wrapper(*args, **kw):
return dispatcher.dispatch(args[1].__class__)(*args, **kw)
wrapper.register = dispatcher.register
update_wrapper(wrapper, dispatcher)
return wrapper
示例11: is_registered_in_singledispatch_function
# 需要导入模块: import functools [as 别名]
# 或者: from functools import singledispatch [as 别名]
def is_registered_in_singledispatch_function(node):
"""Check if the given function node is a singledispatch function."""
singledispatch_qnames = (
'functools.singledispatch',
'singledispatch.singledispatch'
)
if not isinstance(node, astroid.FunctionDef):
return False
decorators = node.decorators.nodes if node.decorators else []
for decorator in decorators:
# func.register are function calls
if not isinstance(decorator, astroid.Call):
continue
func = decorator.func
if not isinstance(func, astroid.Attribute) or func.attrname != 'register':
continue
try:
func_def = next(func.expr.infer())
except astroid.InferenceError:
continue
if isinstance(func_def, astroid.FunctionDef):
return decorated_with(func_def, singledispatch_qnames)
return False
示例12: convert_yielded
# 需要导入模块: import functools [as 别名]
# 或者: from functools import singledispatch [as 别名]
def convert_yielded(yielded: _Yieldable) -> Future:
"""Convert a yielded object into a `.Future`.
The default implementation accepts lists, dictionaries, and
Futures. This has the side effect of starting any coroutines that
did not start themselves, similar to `asyncio.ensure_future`.
If the `~functools.singledispatch` library is available, this function
may be extended to support additional types. For example::
@convert_yielded.register(asyncio.Future)
def _(asyncio_future):
return tornado.platform.asyncio.to_tornado_future(asyncio_future)
.. versionadded:: 4.1
"""
if yielded is None or yielded is moment:
return moment
elif yielded is _null_future:
return _null_future
elif isinstance(yielded, (list, dict)):
return multi(yielded) # type: ignore
elif is_future(yielded):
return typing.cast(Future, yielded)
elif isawaitable(yielded):
return _wrap_awaitable(yielded) # type: ignore
else:
raise BadYieldError("yielded unknown object %r" % (yielded,))
示例13: patch_functools
# 需要导入模块: import functools [as 别名]
# 或者: from functools import singledispatch [as 别名]
def patch_functools() -> None:
functools.singledispatch = tracing_singledispatch
示例14: convert_yielded
# 需要导入模块: import functools [as 别名]
# 或者: from functools import singledispatch [as 别名]
def convert_yielded(yielded):
"""Convert a yielded object into a `.Future`.
The default implementation accepts lists, dictionaries, and Futures.
If the `~functools.singledispatch` library is available, this function
may be extended to support additional types. For example::
@convert_yielded.register(asyncio.Future)
def _(asyncio_future):
return tornado.platform.asyncio.to_tornado_future(asyncio_future)
.. versionadded:: 4.1
"""
# Lists and dicts containing YieldPoints were handled earlier.
if yielded is None or yielded is moment:
return moment
elif yielded is _null_future:
return _null_future
elif isinstance(yielded, (list, dict)):
return multi(yielded)
elif is_future(yielded):
return yielded
elif isawaitable(yielded):
return _wrap_awaitable(yielded)
else:
raise BadYieldError("yielded unknown object %r" % (yielded,))
示例15: method_dispatch
# 需要导入模块: import functools [as 别名]
# 或者: from functools import singledispatch [as 别名]
def method_dispatch(func: Callable[..., Any]) -> Callable[..., Any]:
dispatcher = functools.singledispatch(func)
def wrapper(*args, **kw): # type: ignore
return dispatcher.dispatch(args[1].__class__)(*args, **kw)
wrapper.register = dispatcher.register # type: ignore
wrapper.registry = dispatcher.registry # type: ignore
functools.update_wrapper(wrapper, func)
return wrapper