当前位置: 首页>>代码示例>>Python>>正文


Python functools.singledispatch方法代码示例

本文整理汇总了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,)) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:25,代码来源:gen.py

示例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) 
开发者ID:johnbywater,项目名称:eventsourcing,代码行数:26,代码来源:decorators.py

示例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) 
开发者ID:johnbywater,项目名称:eventsourcing,代码行数:25,代码来源:transcoding_v1.py

示例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 
开发者ID:genomoncology,项目名称:related,代码行数:23,代码来源:functions.py

示例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") 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:24,代码来源:test_functools.py

示例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",)) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:18,代码来源:test_functools.py

示例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 
开发者ID:graphql-python,项目名称:graphene-mongo,代码行数:26,代码来源:utils.py

示例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,)) 
开发者ID:codelv,项目名称:enaml-native,代码行数:27,代码来源:gen.py

示例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 
开发者ID:graphql-python,项目名称:graphene-django,代码行数:23,代码来源:utils.py

示例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 
开发者ID:SeldonIO,项目名称:alibi,代码行数:24,代码来源:wrappers.py

示例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 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:32,代码来源:utils.py

示例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,)) 
开发者ID:opendevops-cn,项目名称:opendevops,代码行数:31,代码来源:gen.py

示例13: patch_functools

# 需要导入模块: import functools [as 别名]
# 或者: from functools import singledispatch [as 别名]
def patch_functools() -> None:
    functools.singledispatch = tracing_singledispatch 
开发者ID:edgedb,项目名称:edgedb,代码行数:4,代码来源:tracing_singledispatch.py

示例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,)) 
开发者ID:tp4a,项目名称:teleport,代码行数:29,代码来源:gen.py

示例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 
开发者ID:Enforcer,项目名称:clean-architecture,代码行数:12,代码来源:method_dispatch.py


注:本文中的functools.singledispatch方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。