Python singledispatch.singledispatch() Examples

The following are 9 code examples of singledispatch.singledispatch(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module singledispatch , or try the search function .
Example #1
Source File: functions.py    From related with MIT License 6 votes vote down vote up
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 
Example #2
Source File: utils.py    From graphene-mongo with MIT License 6 votes vote down vote up
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 
Example #3
Source File: utils.py    From graphene-django with MIT License 6 votes vote down vote up
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 
Example #4
Source File: utils.py    From linter-pylama with MIT License 5 votes vote down vote up
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 
Example #5
Source File: authentication.py    From graceful with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def hash_identifier(identified_with, identifier):
        """Create hash from identifier to be used as a part of user lookup.

        This method is a ``singledispatch`` function. It allows to register
        new implementations for specific authentication middleware classes:

        .. code-block:: python

            from hashlib import sha1

            from graceful.authentication import KeyValueUserStorage, Basic

            @KeyValueUserStorage.hash_identifier.register(Basic)
            def _(identified_with, identifier):
                return ":".join((
                    identifier[0],
                    sha1(identifier[1].encode()).hexdigest(),
                ))

        Args:
            identified_with (str): name of the authentication middleware used
                to identify the user.
            identifier (str): user identifier string

        Return:
            str: hashed identifier string
        """
        if isinstance(identifier, str):
            return identifier
        else:
            raise TypeError(
                "User storage does not support this kind of identifier"
            ) 
Example #6
Source File: json_singledispatch.py    From web_develop with GNU General Public License v3.0 5 votes vote down vote up
def methdispatch(func):
    dispatcher = singledispatch(func)

    def wrapper(*args, **kw):
        return dispatcher.dispatch(args[1].__class__)(*args, **kw)
    wrapper.register = dispatcher.register
    update_wrapper(wrapper, func)
    return wrapper 
Example #7
Source File: decorators.py    From PGPy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def sdmethod(meth):
    """
    This is a hack to monkey patch sdproperty to work as expected with instance methods.
    """
    sd = singledispatch(meth)

    def wrapper(obj, *args, **kwargs):
        return sd.dispatch(args[0].__class__)(obj, *args, **kwargs)

    wrapper.register = sd.register
    wrapper.dispatch = sd.dispatch
    wrapper.registry = sd.registry
    wrapper._clear_cache = sd._clear_cache
    functools.update_wrapper(wrapper, meth)
    return wrapper 
Example #8
Source File: utils.py    From pyGeoPressure with MIT License 5 votes vote down vote up
def methdispatch(func):
    dispatcher = singledispatch(func)
    def wrapper(*args, **kw):
        return dispatcher.dispatch(args[1].__class__)(*args, **kw)
    wrapper.register = dispatcher.register
    update_wrapper(wrapper, func)
    return wrapper 
Example #9
Source File: helper.py    From testrail-python with MIT License 5 votes vote down vote up
def methdispatch(func):
    dispatcher = singledispatch(func)

    def wrapper(*args, **kw):
        try:
            return dispatcher.dispatch(args[1].__class__)(*args, **kw)
        except IndexError:
            return dispatcher.dispatch(args[0].__class__)(*args, **kw)
    wrapper.register = dispatcher.register
    update_wrapper(wrapper, func)
    return wrapper