當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。