Python functools.singledispatch() Examples
The following are 30
code examples of functools.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
functools
, or try the search function
.
Example #1
Source File: gen.py From tornado-zh with MIT License | 6 votes |
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,))
Example #2
Source File: utils.py From graphene-mongo with MIT License | 6 votes |
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: test_functools.py From ironpython3 with Apache License 2.0 | 6 votes |
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",))
Example #4
Source File: gen.py From enaml-native with MIT License | 6 votes |
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,))
Example #5
Source File: test_functools.py From android_universal with MIT License | 6 votes |
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")
Example #6
Source File: test_functools.py From ironpython3 with Apache License 2.0 | 6 votes |
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")
Example #7
Source File: utils.py From graphene-django with MIT License | 6 votes |
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 #8
Source File: test_functools.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
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",))
Example #9
Source File: test_functools.py From android_universal with MIT License | 6 votes |
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",))
Example #10
Source File: gen.py From EventGhost with GNU General Public License v2.0 | 6 votes |
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,))
Example #11
Source File: test_functools.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
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")
Example #12
Source File: wrappers.py From alibi with Apache License 2.0 | 6 votes |
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
Example #13
Source File: test_functools.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 6 votes |
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")
Example #14
Source File: gen.py From tornado-zh with MIT License | 6 votes |
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,))
Example #15
Source File: decorators.py From eventsourcing with BSD 3-Clause "New" or "Revised" License | 6 votes |
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)
Example #16
Source File: transcoding_v1.py From eventsourcing with BSD 3-Clause "New" or "Revised" License | 6 votes |
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)
Example #17
Source File: transcoding.py From eventsourcing with BSD 3-Clause "New" or "Revised" License | 6 votes |
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)
Example #18
Source File: test_functools.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 6 votes |
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",))
Example #19
Source File: functions.py From related with MIT License | 6 votes |
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 #20
Source File: gen.py From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
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,))
Example #21
Source File: util.py From ballistica with MIT License | 5 votes |
def dispatchmethod( func: Callable[[Any, TARG], TRET]) -> DispatchMethodWrapper[TARG, TRET]: """A variation of functools.singledispatch for methods.""" from functools import singledispatch, update_wrapper origwrapper: Any = singledispatch(func) # Pull this out so hopefully origwrapper can die, # otherwise we reference origwrapper in our wrapper. dispatch = origwrapper.dispatch # All we do here is recreate the end of functools.singledispatch # where it returns a wrapper except instead of the wrapper using the # first arg to the function ours uses the second (to skip 'self'). # This was made with Python 3.7; we should probably check up on # this in later versions in case anything has changed. # (or hopefully they'll add this functionality to their version) def wrapper(*args: Any, **kw: Any) -> Any: if not args or len(args) < 2: raise TypeError(f'{funcname} requires at least ' '2 positional arguments') return dispatch(args[1].__class__)(*args, **kw) funcname = getattr(func, '__name__', 'dispatchmethod method') wrapper.register = origwrapper.register # type: ignore wrapper.dispatch = dispatch # type: ignore wrapper.registry = origwrapper.registry # type: ignore # pylint: disable=protected-access wrapper._clear_cache = origwrapper._clear_cache # type: ignore update_wrapper(wrapper, func) # pylint: enable=protected-access return cast(DispatchMethodWrapper, wrapper)
Example #22
Source File: _internal.py From sisl with GNU Lesser General Public License v3.0 | 5 votes |
def __init__(self, func): if not callable(func) and not hasattr(func, "__get__"): raise TypeError("{!r} is not callable or a descriptor".format(func)) self.dispatcher = singledispatch(func) self.func = func
Example #23
Source File: singledispatch.py From lightbus with Apache License 2.0 | 5 votes |
def singledispatchmethod(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 #24
Source File: siu.py From siuba with MIT License | 5 votes |
def symbolic_dispatch(f = None, cls = object): if f is None: return lambda f: symbolic_dispatch(f, cls) # TODO: don't use singledispatch if it has already been done dispatch_func = singledispatch(f) if cls is not object: dispatch_func.register(cls, f) dispatch_func.register(object, _dispatch_not_impl(dispatch_func.__name__)) @dispatch_func.register(Symbolic) def _dispatch_symbol(__data, *args, **kwargs): return create_sym_call(FuncArg(dispatch_func), strip_symbolic(__data), *args, **kwargs) @dispatch_func.register(Call) def _dispatch_call(__data, *args, **kwargs): # TODO: want to just create call, for now use hack of creating a symbolic # call and getting the source off of it... return strip_symbolic(create_sym_call(FuncArg(dispatch_func), __data, *args, **kwargs)) return dispatch_func # Do some gnarly method setting -----------------------------------------------
Example #25
Source File: utils.py From pyecore with BSD 3-Clause "New" or "Revised" License | 5 votes |
def dispatch(func): dispatcher = singledispatch(func) def wrapper(*args, **kw): return dispatcher.dispatch(args[1].__class__)(*args, **kw) def register(cls, func=None): if isinstance(cls, EObject): return dispatcher.register(cls.python_class) return dispatcher.register(cls) wrapper.register = register update_wrapper(wrapper, func) return wrapper # def install_issubclass_patch(): # old_issubclass = builtins.issubclass # # def pyecore_issubclass(self, cls): # if isinstance(self, EClass): # return old_issubclass(self.python_class, cls) # return old_issubclass(self, cls) # pyecore_issubclass.original = old_issubclass # builtins.issubclass = pyecore_issubclass # # # class original_issubclass(object): # def __init__(self): # self.pyecore_issubclass = builtins.issubclass # # def __enter__(self): # builtins.issubclass = self.pyecore_issubclass.original # # def __exit__(self, type_, value, traceback): # builtins.issubclass = self.pyecore_issubclass
Example #26
Source File: utils.py From pyGeoPressure with MIT License | 5 votes |
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 #27
Source File: data_reader.py From open_model_zoo with Apache License 2.0 | 5 votes |
def __init__(self, data_source, config=None, **kwargs): self.config = config self.data_source = data_source self.read_dispatcher = singledispatch(self.read) self.read_dispatcher.register(list, self._read_list) self.read_dispatcher.register(ClipIdentifier, self._read_clip) self.read_dispatcher.register(MultiFramesInputIdentifier, self._read_frames_multi_input) self.validate_config() self.configure()
Example #28
Source File: regression.py From open_model_zoo with Apache License 2.0 | 5 votes |
def __init__(self, value_differ, *args, **kwargs): super().__init__(*args, **kwargs) self.value_differ = value_differ self.calculate_diff = singledispatch(self._calculate_diff_regression_rep) self.calculate_diff.register(DepthEstimationAnnotation, self._calculate_diff_depth_estimation_rep)
Example #29
Source File: verbs.py From siuba with MIT License | 5 votes |
def singledispatch2(cls, f = None): """Wrap singledispatch. Making sure to keep its attributes on the wrapper. This wrapper has three jobs: 1. strip symbols off of calls 2. pass NoArgs instance for calls like some_func(), so dispatcher can handle 3. return a Pipeable when the first arg of a call is a symbol """ # classic way of allowing args to a decorator if f is None: return lambda f: singledispatch2(cls, f) # initially registers func for object, so need to change to pd.DataFrame dispatch_func = singledispatch(f) if isinstance(cls, tuple): for c in cls: dispatch_func.register(c, f) else: dispatch_func.register(cls, f) # then, set the default object dispatcher to create a pipe register_pipe(dispatch_func, object) # register dispatcher for Call, and NoArgs pipe_call(dispatch_func) pipe_no_args(dispatch_func) @wraps(dispatch_func) def wrapper(*args, **kwargs): strip_args = map(strip_symbolic, args) strip_kwargs = {k: strip_symbolic(v) for k,v in kwargs.items()} if not args: return dispatch_func(NoArgs(), **strip_kwargs) return dispatch_func(*strip_args, **strip_kwargs) return wrapper
Example #30
Source File: mutation.py From caluma with GNU General Public License v3.0 | 5 votes |
def get_mutation_params(info): @singledispatch def _parse_ast_value(arg, info): # pragma: no cover raise RuntimeError(f"Unknown arg {arg}") @_parse_ast_value.register(ast.ObjectValue) def _(arg, info): return { field.name.value: _parse_ast_value(field.value, info) for field in arg.fields } @_parse_ast_value.register(ast.ListValue) def _(arg, info): return [_parse_ast_value(val, info) for val in arg.values] @_parse_ast_value.register(ast.StringValue) def _(arg, info): return arg.value @_parse_ast_value.register(ast.Variable) def _(arg, info): return info.variable_values[arg.name.value] # No need to keep the registered singledispatch implementation # in the namespace del _ current_sel = [ sel for sel in info.operation.selection_set.selections if sel.name.value == info.field_name # if aliases are used, we need to compare them as well and (sel.alias is None or sel.alias.value == info.path[0]) ][0] return { arg.name.value: _parse_ast_value(arg.value, info) for arg in current_sel.arguments }