Skip to main content
https://img.shields.io/pypi/v/singledispatch.svg https://img.shields.io/pypi/pyversions/singledispatch.svg tests Code style: Black

PEP 443 proposed to expose a mechanism in the functools standard library module in Python 3.4 that provides a simple form of generic programming known as single-dispatch generic functions.

This library is a backport of this functionality to Python 2.6 - 3.3.

To define a generic function, decorate it with the @singledispatch decorator. Note that the dispatch happens on the type of the first argument, create your function accordingly:

>>> from singledispatch import singledispatch
>>> @singledispatch
... def fun(arg, verbose=False):
...     if verbose:
...         print("Let me just say,", end=" ")
...     print(arg)

To add overloaded implementations to the function, use the register() attribute of the generic function. It is a decorator, taking a type parameter and decorating a function implementing the operation for that type:

>>> @fun.register(int)
... def _(arg, verbose=False):
...     if verbose:
...         print("Strength in numbers, eh?", end=" ")
...     print(arg)
...
>>> @fun.register(list)
... def _(arg, verbose=False):
...     if verbose:
...         print("Enumerate this:")
...     for i, elem in enumerate(arg):
...         print(i, elem)

To enable registering lambdas and pre-existing functions, the register() attribute can be used in a functional form:

>>> def nothing(arg, verbose=False):
...     print("Nothing.")
...
>>> fun.register(type(None), nothing)

The register() attribute returns the undecorated function which enables decorator stacking, pickling, as well as creating unit tests for each variant independently:

>>> @fun.register(float)
... @fun.register(Decimal)
... def fun_num(arg, verbose=False):
...     if verbose:
...         print("Half of your number:", end=" ")
...     print(arg / 2)
...
>>> fun_num is fun
False

When called, the generic function dispatches on the type of the first argument:

>>> fun("Hello, world.")
Hello, world.
>>> fun("test.", verbose=True)
Let me just say, test.
>>> fun(42, verbose=True)
Strength in numbers, eh? 42
>>> fun(['spam', 'spam', 'eggs', 'spam'], verbose=True)
Enumerate this:
0 spam
1 spam
2 eggs
3 spam
>>> fun(None)
Nothing.
>>> fun(1.23)
0.615

Where there is no registered implementation for a specific type, its method resolution order is used to find a more generic implementation. The original function decorated with @singledispatch is registered for the base object type, which means it is used if no better implementation is found.

To check which implementation will the generic function choose for a given type, use the dispatch() attribute:

>>> fun.dispatch(float)
<function fun_num at 0x1035a2840>
>>> fun.dispatch(dict)    # note: default implementation
<function fun at 0x103fe0000>

To access all registered implementations, use the read-only registry attribute:

>>> fun.registry.keys()
dict_keys([<class 'NoneType'>, <class 'int'>, <class 'object'>,
          <class 'decimal.Decimal'>, <class 'list'>,
          <class 'float'>])
>>> fun.registry[float]
<function fun_num at 0x1035a2840>
>>> fun.registry[object]
<function fun at 0x103fe0000>

The vanilla documentation is available at http://docs.python.org/3/library/functools.html#functools.singledispatch.

Maintenance

This backport is maintained on Github by Jason R. Coombs, one of the members of the core CPython team:

Conversion Process

This section is technical and should bother you only if you are wondering how this backport is produced. If the implementation details of this backport are not important for you, feel free to ignore the following content.

singledispatch is converted using six so that a single codebase can be used for all compatible Python versions. Because a fully automatic conversion was not doable, I took the following branching approach:

  • the upstream branch holds unchanged files synchronized from the upstream CPython repository. The synchronization is currently done by manually copying the required code parts and stating from which CPython changeset they come from. The tests should pass on Python 3.4 on this branch.

  • the default branch holds the manually translated version and this is where all tests are run for all supported Python versions using Tox.

Release files for singledispatch 3.5.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for singledispatch 3.5.0
File Size Uploaded
singledispatch-3.5.0.tar.gz 22.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for singledispatch 3.5.0
File Interpreter ABI Platform
singledispatch-3.5.0-py2.py3-none-any.whl Python 2, Python 3 none any Details

Total release size: 31.4 kB

Release files / singledispatch-3.5.0.tar.gz

Download URL singledispatch-3.5.0.tar.gz
Size 22.2 kB
Tags Source
SHA-256 checksum
How to use checksums
b5b6d32674e519b48a2186c0c1e68a751a9d789a30c34a9ba8cb04d9e505ea22
BLAKE2b-256 checksum
How to use checksums
49f7b6f0f6a2fbe8f3208af412d2a3b97cf755ae79c6cfc04c564b1c6d787b8f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.3.0 pkginfo/1.7.0 requests/2.25.1 setuptools/52.0.0 requests-toolbelt/0.9.1 tqdm/4.57.0 CPython/3.9.1

Release files / singledispatch-3.5.0-py2.py3-none-any.whl

Download URL singledispatch-3.5.0-py2.py3-none-any.whl
Size 9.2 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
d236af5e26d115ea8886335e5c3dcad499c4ea2934b41d3660952a7894962d99
BLAKE2b-256 checksum
How to use checksums
b961300bcf49ae23c40af4fad86fa1efad0fa361f8877e61351e2702f1ff0622
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.3.0 pkginfo/1.7.0 requests/2.25.1 setuptools/52.0.0 requests-toolbelt/0.9.1 tqdm/4.57.0 CPython/3.9.1

Release history Release notifications | RSS feed

4.1.2

2 release files

4.1.1

2 release files

4.1.0

2 release files

4.0.0

2 release files

3.7.0

2 release files

3.6.2

2 release files

3.6.1

2 release files

3.6.0

2 release files

This release

3.5.0 This release

2 release files

3.4.0.1

1 release file

3.4.0.0

1 release file

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page