Skip to main content

Multimethod-dispatcher

Tests and Release CodeQL Build and Publish

This module that enables the use of the same function name but with variable dispatch keys. This allows different object types or values to execute different functions but with the same name. Similar to Object Orientation where objects can have their own implementation of a function, this is the functional response to this. Similar to Clojure's Multimethod

This originates from Alex Bard's blog post

There are two annotations:

  • @multi evaluates the arguments to return a unique key which determines which method is called.
  • @method is used to declare how that unique key is handled

The following code is an example of having multiple dictionaries with common elements, but handling the equation differently.

from multimethod import method, multi

@multi
def area(shape):
    """Multimethod dispatch key"""
    return shape.get('type')


@method(area, 'rectangle')
def area(rectangle):
    """Get area of a rectangle"""
    return rectangle.get('width') * rectangle.get('height')


@method(area, 'circle')
def area(circle):
    """Get area of a circle"""
    return circle.get('radius') ** 2 * 3.14159

area({'type': 'circle', 'radius': 0.5}) # => 0.7853975
area({'type': 'rectangle', 'width': 5, 'height': 8}) # => 40

This example is a more complicated version, evaluating on type and has a optional parameter for date of birth

from datetime import datetime
from multimethod import method, multi


class Person:
    """Person object to hold name and dob"""
    def __init__(self, name, dob):
        self.name = name
        self.dob = datetime.strptime(dob, '%Y-%m-%d')

    def get_name(self):
        """Return name"""
        return self.name

    def get_dob_as_str(self):
        """Return dob as string"""
        return self.dob.strftime('%Y-%m-%d')

@multi
def get_name(obj, _=None):
    """Multimethod dispatch key"""
    return obj.__class__


@method(get_name, dict)
def get_name(obj, _=None):
    """Dictionary function for getting name and dob from dict"""
    return "{} is born on {}".format(obj.get('name'), obj.get('dob'))


@method(get_name, str)
def get_name(obj, dob):
    """Dictionary function for getting name and dob from string"""
    return "{} is born on {}".format(obj, dob)


@method(get_name, Person)
def get_name(obj, _=None):
    """Person object type for getting name and dob"""
    return "{} is born on {}".format(obj.get_name(), obj.get_dob_as_str())


@method(get_name)  # Default
def get_name(*args, **kwargs):  # pylint: disable=W0613
    """Default response for any other object type"""
    return "No name"


person = Person('Steve', '2019-06-01')
get_name(person) # => 'Steve is born on 2019-06-01'
get_name({'name': 'Tom', 'dob': '2019-06-01'}) # => 'Tom is born on 2019-06-01'
get_name('George', '2019-06-01') # => 'George is born on 2019-06-01'
get_name(2) # => "No name"

Metadata

Release files for multimethod-dispatcher 1.0.2

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

Source distribution (sdist)

Source distribution for multimethod-dispatcher 1.0.2
File Size Uploaded
multimethod-dispatcher-1.0.2.tar.gz 7.1 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for multimethod-dispatcher 1.0.2
File Interpreter ABI Platform
multimethod_dispatcher-1.0.2-py3-none-any.whl Python 3 none any Details

Total release size: 14.5 kB

Release files / multimethod-dispatcher-1.0.2.tar.gz

Download URL multimethod-dispatcher-1.0.2.tar.gz
Size 7.1 kB
Tags Source
SHA-256 checksum
How to use checksums
5aac005d4498bdb80def91ed1eed1c632bb28bbef6810650125af8950ae02f7d
BLAKE2b-256 checksum
How to use checksums
71d8722710fdc245de416c75ee3f97b4d9abdbabb3352a8d5eb988c3c4d35243
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.4.2 importlib_metadata/4.6.3 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.0 CPython/3.9.6

Release files / multimethod_dispatcher-1.0.2-py3-none-any.whl

Download URL multimethod_dispatcher-1.0.2-py3-none-any.whl
Size 7.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7f6cdf6dd1739e45062db2fbfb4a1d3f2afbad63b25a5a85533c0d6a316f969b
BLAKE2b-256 checksum
How to use checksums
c6f8065b5701ba228c633fba2eee5792dacb26dd1dcabf4b632e07d249d38393
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.4.2 importlib_metadata/4.6.3 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.0 CPython/3.9.6

Release history Release notifications | RSS feed

This release

1.0.2 This release

2 release files

1.0.1

2 release files

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