Overloading Python functions
Project description
Ovld
Multiple dispatch in Python, with some extra features.
With ovld, you can write a version of the same function for every type signature using annotations instead of writing an awkward sequence of isinstance statements. Unlike Python singledispatch, it works for multiple arguments.
Other features of ovld:
- Multiple dispatch for methods (with
metaclass=ovld.OvldMC) - Create variants of functions
- Built-in support for extensible, stateful recursion
- Function wrappers
- Function postprocessors
- Nice stack traces
Example
Here's a function that adds lists, tuples and dictionaries:
from ovld import ovld
@ovld
def add(x: list, y: list):
return [add(a, b) for a, b in zip(x, y)]
@ovld
def add(x: tuple, y: tuple):
return tuple(add(a, b) for a, b in zip(x, y))
@ovld
def add(x: dict, y: dict):
return {k: add(v, y[k]) for k, v in x.items()}
@ovld
def add(x: object, y: object):
return x + y
Bootstrapping and variants
Now, there is another way to do this using ovld's auto-bootstrapping. Simply list self as the first argument to the function, and self will be bound to the function itself, so you can call self(x, y) for the recursion instead of add(x, y):
@ovld
def add(self, x: list, y: list):
return [self(a, b) for a, b in zip(x, y)]
@ovld
def add(self, x: tuple, y: tuple):
return tuple(self(a, b) for a, b in zip(x, y))
@ovld
def add(self, x: dict, y: dict):
return {k: self(v, y[k]) for k, v in x.items()}
@ovld
def add(self, x: object, y: object):
return x + y
Why is this useful, though? Observe:
@add.variant
def mul(self, x: object, y: object):
return x * y
assert add([1, 2], [3, 4]) == [4, 6]
assert mul([1, 2], [3, 4]) == [3, 8]
A variant of a function is a copy which inherits all of the original's implementations but may define new ones. And because self is bound to the function that's called at the top level, the implementations for list, tuple and dict will bind self to add or mul depending on which one was called.
State
You can pass initial_state to @ovld or variant. The initial state must be a function that takes no arguments. Its return value will be available in self.state. The state is initialized at the top level call, but recursive calls to self will preserve it.
In other words, you can do something like this:
@add.variant(initial_state=lambda: 0)
def count(self, x, y):
self.state += 1
return (f"#{self.state}", x + y)
assert count([1, 2, 3], [4, 5, 6]) == [("#1", 5), ("#2", 7), ("#3", 9)]
The initial_state function can return any object and you can use the state to any purpose (e.g. cache or memoization).
Custom dispatch
You can define your own dispatching function. The dispatcher's first argument is always self.
self.resolve(x, y)to get the right function for the types of x and yself[type(x), type(y)]will also return the right function for these types, but it works directly with the types.
For example, here is how you might define a function such that f(x) <=> f(x, x):
@ovld.dispatch
def add_default(self, x, y=None):
if y is None:
y = x
return self.resolve(x, y)(x, y)
@ovld
def add_default(x: int, y: int):
return x + y
@ovld
def add_default(x: str, y: str):
return x + y
@ovld
def add_default(xs: list, ys: list):
return [add_default(x, y) for x, y in zip(xs, ys)]
assert add_default([1, 2, "alouette"]) == [2, 4, "alouettealouette"]
There are other uses for this feature, e.g. memoization.
The normal functions may also have a self, which works the same as bootstrapping, and you can give an initial_state to @ovld.dispatch as well.
Postprocess
@ovld, @ovld.dispatch, etc. take a postprocess argument which should be a function of one argument. That function will be called with the result of the call and must return the final result of the call.
Note that intermediate, bootstrapped recursive calls (recursive calls using self()) will not be postprocessed (if you want to wrap these calls, you can do so otherwise, like defining a custom dispatch). Only the result of the top level call is postprocessed.
Methods
Use the OvldMC metaclass to use multiple dispatch on methods. In this case there is no bootstrapping as described above and self is simply bound to the class instance.
from ovld import OvldMC
class Cat(metaclass=OvldMC):
def interact(self, x: Mouse):
return "catch"
def interact(self, x: Food):
return "devour"
def interact(self, x: PricelessVase):
return "destroy"
Ambiguous calls
The following definitions will cause a TypeError at runtime when called with two ints, because it is unclear which function is the right match:
@ovld
def ambig(x: int, y: object):
print("io")
@ovld
def ambig(x: object, y: int):
print("oi")
ambig(8, 8) # ???
You may define an additional function with signature (int, int) to disambiguate:
@ovld
def ambig(x: int, y: int):
print("ii")
Other features
Tracebacks
ovld automagically renames functions so that the stack trace is more informative:
@add.variant
def bad(self, x: object, y: object):
raise Exception("Bad.")
bad([1], [2])
"""
File "/Users/breuleuo/code/ovld/ovld/core.py", line 148, in bad.entry
res = ovc(*args, **kwargs)
File "/Users/breuleuo/code/ovld/ovld/core.py", line 182, in bad.dispatch
return method(self.bind_to, *args, **kwargs)
File "example.py", line 6, in bad[list, list]
return [self(a, b) for a, b in zip(x, y)]
File "example.py", line 6, in <listcomp>
return [self(a, b) for a, b in zip(x, y)]
File "/Users/breuleuo/code/ovld/ovld/core.py", line 182, in bad.dispatch
return method(self.bind_to, *args, **kwargs)
File "example.py", line 26, in bad[*, *]
raise Exception("Bad.")
Exception: Bad.
"""
The functions on the stack have names like bad.entry, bad.dispatch, bad[list, list] and bad[*, *] (* stands for object), which lets you better understand what happened just from the stack trace.
This also means profilers will be able to differentiate between these paths and between variants, even if they share code paths.
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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file ovld-0.1.8.tar.gz.
File metadata
- Download URL: ovld-0.1.8.tar.gz
- Upload date:
- Size: 13.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.0.0b3 CPython/3.7.7 Darwin/19.6.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
fda4766211d007ad988ec1893e1509923afa1ecbdc826df2555fa95a4a2af569
|
|
| MD5 |
47b0c90cb17061d7d695a4f8e0fbafb7
|
|
| BLAKE2b-256 |
27cacd1f502722a0e763e544f98b13ba0309ad95f34eb9e231b6fd5a8300b3c6
|
File details
Details for the file ovld-0.1.8-py3-none-any.whl.
File metadata
- Download URL: ovld-0.1.8-py3-none-any.whl
- Upload date:
- Size: 12.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.0.0b3 CPython/3.7.7 Darwin/19.6.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
4bc431cdf3f08543123731e93d9d582f1deb2a9abf6004c2b41fa90f1a6324a0
|
|
| MD5 |
a82bb55b6ba007b50048b16a1be22f36
|
|
| BLAKE2b-256 |
4d3038c4b04b9cfec55d741598e1204140e5156c9dc0fd922b38a00ad0c1bed9
|