=========================
Trivial Generic Functions
=========================
* New in 0.8: Source and tests are compatible with Python 3 (w/o ``setup.py``)
* 0.8.1: setup.py is now compatible with Python 3 as well
* New in 0.7: `Multiple Types or Objects`_
* New in 0.6: `Inspection and Extension`_, and thread-safe method registration
The ``simplegeneric`` module lets you define simple single-dispatch
generic functions, akin to Python's built-in generic functions like
``len()``, ``iter()`` and so on. However, instead of using
specially-named methods, these generic functions use simple lookup
tables, akin to those used by e.g. ``pickle.dump()`` and other
generic functions found in the Python standard library.
As you can see from the above examples, generic functions are actually
quite common in Python already, but there is no standard way to create
simple ones. This library attempts to fill that gap, as generic
functions are an `excellent alternative to the Visitor pattern`_, as
well as being a great substitute for most common uses of adaptation.
This library tries to be the simplest possible implementation of generic
functions, and it therefore eschews the use of multiple or predicate
dispatch, as well as avoiding speedup techniques such as C dispatching
or code generation. But it has absolutely no dependencies, other than
Python 2.4, and the implementation is just a single Python module of
less than 100 lines.
Usage
-----
Defining and using a generic function is straightforward::
>>> from simplegeneric import generic
>>> @generic
... def move(item, target):
... """Default implementation goes here"""
... print("what you say?!")
>>> @move.when_type(int)
... def move_int(item, target):
... print("In AD %d, %s was beginning." % (item, target))
>>> @move.when_type(str)
... def move_str(item, target):
... print("How are you %s!!" % item)
... print("All your %s are belong to us." % (target,))
>>> zig = object()
>>> @move.when_object(zig)
... def move_zig(item, target):
... print("You know what you %s." % (target,))
... print("For great justice!")
>>> move(2101, "war")
In AD 2101, war was beginning.
>>> move("gentlemen", "base")
How are you gentlemen!!
All your base are belong to us.
>>> move(zig, "doing")
You know what you doing.
For great justice!
>>> move(27.0, 56.2)
what you say?!
Inheritance and Allowed Types
-----------------------------
Defining multiple methods for the same type or object is an error::
>>> @move.when_type(str)
... def this_is_wrong(item, target):
... pass
Traceback (most recent call last):
...
TypeError: already has method for type <...'str'>
>>> @move.when_object(zig)
... def this_is_wrong(item, target): pass
Traceback (most recent call last):
...
TypeError: already has method for object