Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/ikalnytskyi/singledispatchmethod
Backport of 'functools.singledispatchmethod' from Python 3.8 to Python 2.7 - 3.7.
https://github.com/ikalnytskyi/singledispatchmethod
backport python singledispatch
Last synced: 14 days ago
JSON representation
Backport of 'functools.singledispatchmethod' from Python 3.8 to Python 2.7 - 3.7.
- Host: GitHub
- URL: https://github.com/ikalnytskyi/singledispatchmethod
- Owner: ikalnytskyi
- License: other
- Created: 2019-08-11T14:18:07.000Z (about 5 years ago)
- Default Branch: master
- Last Pushed: 2019-08-12T07:15:12.000Z (about 5 years ago)
- Last Synced: 2024-10-04T15:37:48.055Z (about 1 month ago)
- Topics: backport, python, singledispatch
- Language: Python
- Homepage:
- Size: 6.84 KB
- Stars: 15
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.rst
- License: LICENSE
Awesome Lists containing this project
README
singledispatchmethod
====================Backport of ``@functools.singledispatchmethod`` decorator [1]_ from
Python 3.8 to Python 2.7-3.7. These are merely ~30 lines of code, but
why bother yourself with copypasta?.. code:: bash
$ pip install singledispatchmethod
The decorator transforms a method into a single-dispatch [2]_ generic
function [3]_. Note that since the dispatch happens on the type of the
first non-self or non-cls argument, you have to create your function
accordingly:.. code:: python
from singledispatchmethod import singledispatchmethod
class Negator:
@singledispatchmethod
def neg(self, arg):
raise NotImplementedError("Cannot negate a")@neg.register
def _(self, arg: int):
return -arg@neg.register
def _(self, arg: bool):
return not arg``@singledispatchmethod`` supports nesting with other decorators such as
``@classmethod``. However, in order to expose ``dispatcher.register``,
``@singledispatchmethod`` must be the *outer most* decorator. Here is
the ``Negator`` class with the ``neg`` methods being class bound:.. code:: python
from singledispatchmethod import singledispatchmethod
class Negator:
@singledispatchmethod
@classmethod
def neg(cls, arg):
raise NotImplementedError("Cannot negate a")@neg.register
@classmethod
def _(cls, arg: int):
return -arg@neg.register
@classmethod
def _(cls, arg: bool):
return not argThe same pattern can be used for other similar decorators, such as
``@staticmethod`` or ``@abstractmethod``. Please note, since
``@singledispatchmethod`` decorator is based on
``@functools.singledispatch``, type annotations are supported by
``dispatcher.register`` only since Python 3.7... [1] https://docs.python.org/3.8/library/functools.html#functools.singledispatchmethod
.. [2] https://docs.python.org/3.8/glossary.html#term-single-dispatch
.. [3] https://docs.python.org/3.8/glossary.html#term-generic-function