All Projects → wesselb → plum

wesselb / plum

Licence: MIT license
Multiple dispatch in Python

Programming Languages

python
139335 projects - #7 most used programming language
Makefile
30231 projects

Projects that are alternatives of or similar to plum

Revisited
🧑‍🤝‍🧑 The visitor pattern revisited. An inheritance-aware acyclic visitor template, any and any-function templates.
Stars: ✭ 14 (-95.14%)
Mutual labels:  multiple-dispatch
unpythonic
Supercharge your Python with parts of Lisp and Haskell.
Stars: ✭ 53 (-81.6%)
Mutual labels:  multiple-dispatch

Plum: Multiple Dispatch in Python

DOI CI Coverage Status Latest Docs Code style: black

Everybody likes multiple dispatch, just like everybody likes plums.

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", signature Signature(builtins.object) 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 "fallback implementation of multiplication"


@dispatch
def multiply(x: Real, y: Real):
    return "specialised implementation for reals"


@dispatch
def multiply(x: Rational, y: Rational):
    return "specialised implementation for rationals"
>>> multiply(1, 1)
'specialised implementation for rationals'

>>> multiply(1.0, 1.0)
'specialised implementation for reals'

>>> multiply(1j, 1j)
'fallback implementation of multiplication'

>>> multiply(1, 1.0)  # For mixed types, it automatically chooses the right optimisation!
'specialised implementation for reals'
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].