Dynamic Dispatch by Type

This module provides a decorator that lets you choose which method is called via type specifications.

Hint

There is a good example of the decorator in use in the source for Encoder; more details are available in the paper Algebraic ABCs.

pytyp.spec.dispatch.overload(default)

This is the decorator for dynamic dispatch by type. It should be placed on the default method - it is that method whose name will be called for all the overloaded methods.

Additional methods are then marked by a decorator that is .intercept on the default. For example:

class MyClass:

    @overload
    def default_method(self, foo, bar):
        # code here runs if foo is not a sequence (or list)

    @default_method.intercept
    def foo_seq(self, foo:Sequence, bar):
        # code here runs if foo is a sequence (but not a string!)

    @default_method.intercept
    def foo_list(self, foo:list, bar):
        # code here runs if foo is a list

In the example above, when default_method() is called, any of the three methods might be used, depending on the type of foo.

The order in which methods are checked is “bottom to top” and a method can pass the call “up” by calling .previous() on itself. So, for example, code in foo_list() can call foo_seq() via self.foo_list.previous().

class pytyp.spec.dispatch.Overload(default)[source]

This class implements the overload decorator via the constructor. It implements a data descriptor that returns the wrapper method (and the .intercept() method, used to add additional methods).

Previous topic

Verification (pytyp.spec.check)

Next topic

Licence

This Page