Multiple dispatch in Python
Project description
Plum: Multiple Dispatch in Python
Everybody likes multiple dispatch, just like everybody likes plums.
Note: Plum 2 is now powered by Beartype! If you notice any issues with the new release, please open an issue.
Installation
Plum requires Python 3.7 or higher.
pip install plum-dispatch
Documentation
See here.
What's This?
Plum brings your type annotations to life:
from numbers import Number
from plum import dispatch
@dispatch
def f(x: str):
return "This is a string!"
@dispatch
def f(x: int):
return "This is an integer!"
@dispatch
def f(x: Number):
return "This is a general number, but I don't know which type."
>>> f("1")
'This is a string!'
>>> f(1)
'This is an integer!'
>>> f(1.0)
'This is a number, but I don't know which type.'
>>> f(object())
NotFoundLookupError: For function `f`, `(<object object at 0x7fb528458190>,)` could not be resolved.
This also works for multiple arguments, enabling some neat design patterns:
from numbers import Number, Real, Rational
from plum import dispatch
@dispatch
def multiply(x: Number, y: Number):
return "Performing fallback implementation of multiplication..."
@dispatch
def multiply(x: Real, y: Real):
return "Performing specialised implementation for reals..."
@dispatch
def multiply(x: Rational, y: Rational):
return "Performing specialised implementation for rationals..."
>>> multiply(1, 1)
'Performing specialised implementation for rationals...'
>>> multiply(1.0, 1.0)
'Performing specialised implementation for reals...'
>>> multiply(1j, 1j)
'Performing fallback implementation of multiplication...'
>>> multiply(1, 1.0) # For mixed types, it automatically chooses the right optimisation!
'Performing specialised implementation for reals...'
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
plum-dispatch-2.0.0.tar.gz
(67.2 kB
view hashes)
Built Distribution
Close
Hashes for plum_dispatch-2.0.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | da7227c065e45f553f4437a2fe21162c547ebb7e4288d36f85bc018b51d649b0 |
|
MD5 | 610819429ab56ba4cd9fe3aa4a23e558 |
|
BLAKE2b-256 | 4d26969c4982e826d5eb79baf5848522eb3cc75e230631b5b3f533206ca52620 |