Simple generic functions

0.8.1 · maintenance · verified Mon Apr 13

The `simplegeneric` module enables the creation of simple single-dispatch generic functions in Python, akin to built-in functions like `len()` or `iter()`. It achieves this through internal lookup tables rather than special method names. The library, currently at version 0.8.1, was last updated in 2012, signifying a mature but no longer actively developed project that remains functional for its intended purpose. It boasts no external runtime dependencies beyond a minimum Python version.

Warnings

Install

Imports

Quickstart

Define a generic function using `@generic` and specialize implementations based on the type or identity of the first argument using `@func.when_type` or `@func.when_object`.

from simplegeneric import generic

@generic
def move(item, target):
    """Default implementation"""
    return f"Default move: {item} to {target}"

@move.when_type(int)
def move_int(item, target):
    return f"Moving integer {item} to AD {target}"

@move.when_type(str)
def move_str(item, target):
    return f"Moving string '{item}' to {target}. All your {target} are belong to us."

class Zig: pass
zig_instance = Zig()

@move.when_object(zig_instance)
def move_zig(item, target):
    return f"Special move for Zig object: {item} to {target}. For great justice!"

assert move(2101, "war") == "Moving integer 2101 to AD war"
assert move("gentlemen", "base") == "Moving string 'gentlemen' to base. All your base are belong to us."
assert move(zig_instance, "doing") == "Special move for Zig object: <object of type Zig> to doing. For great justice!"
assert move(27.0, 56.2) == "Default move: 27.0 to 56.2"

view raw JSON →