methoddispatch


Namemethoddispatch JSON
Version 5.0.1 PyPI version JSON
download
home_pagehttps://github.com/seequent/methoddispatch
Summarysingledispatch decorator for class methods.
upload_time2023-11-21 03:37:12
maintainer
docs_urlNone
authorSeequent Ltd
requires_python
licenseBSD
keywords single dispatch decorator method
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI
coveralls test coverage No coveralls.
            methoddispatch
==============


Python 3.4 added the ``singledispatch`` decorator to the ``functools`` standard library module.
Python 3.8 added the ``singledispatchmethod`` decorator to the ``functools`` standard library module,
however it does not allow sub-classes to modify the dispatch table independantly of the base class.

This library adds this functionality.

To define a generic method , decorate it with the ``@singledispatch`` decorator. Note that the dispatch happens on the type of the first argument, create your function accordingly.
To add overloaded implementations to the function, use the ``register()`` attribute of the generic function.
It is a decorator, taking a type parameter and decorating a function implementing the operation for that type.
The ``register()`` attribute returns the undecorated function which enables decorator stacking, pickling, as well as creating unit tests for each variant independently

>>> from methoddispatch import singledispatch, SingleDispatch
>>> from decimal import Decimal
>>> class MyClass(SingleDispatch):
...     @singledispatch
...     def fun(self, arg, verbose=False):
...         if verbose:
...             print("Let me just say,", end=" ")
...         print(arg)
...
...     @fun.register(int)
...     def fun_int(self, arg, verbose=False):
...         if verbose:
...             print("Strength in numbers, eh?", end=" ")
...         print(arg)
...
...     @fun.register(list)
...     def fun_list(self, arg, verbose=False):
...         if verbose:
...             print("Enumerate this:")
...         for i, elem in enumerate(arg):
...             print(i, elem)
...
...     @fun.register(float)
...     @fun.register(Decimal)
...     def fun_num(obj, arg, verbose=False):
...         if verbose:
...             print("Half of your number:", end=" ")
...         print(arg / 2)

The ``register()`` method relys on ``SingleDispatch.__init_subclass__``
to create the actual dispatch table rather than adding the function directly.
This also means that (unlike functools.singledispatchmethod) two methods
with the same name cannot be registered as only the last one will be in the class dictionary.

Functions not defined in the class can be registered with a generic method using the ``add_overload`` method.

>>> def nothing(obj, arg, verbose=False):
...    print('Nothing.')
>>> MyClass.fun.add_overload(type(None), nothing)

Using ``add_overload`` will affect all instances of ``MyClass`` as if it were part of the class declaration.
When called, the generic function dispatches on the type of the first argument

>>> a = MyClass()
>>> a.fun("Hello, world.")
Hello, world.
>>> a.fun("test.", verbose=True)
Let me just say, test.
>>> a.fun(42, verbose=True)
Strength in numbers, eh? 42
>>> a.fun(['spam', 'spam', 'eggs', 'spam'], verbose=True)
Enumerate this:
0 spam
1 spam
2 eggs
3 spam
>>> a.fun(None)
Nothing.
>>> a.fun(1.23)
0.615

Where there is no registered implementation for a specific type, its method resolution order is used to find a more generic implementation.
The original function decorated with ``@singledispatch`` is registered for the base ``object`` type, which means it is used if no better implementation is found.

To check which implementation will the generic function choose for a given type, use the ``dispatch()`` method

>>> a.fun.dispatch(float)
<function MyClass.fun_num at 0x1035a2840>
>>> a.fun.dispatch(dict)    # note: default implementation
<function MyClass.fun at 0x103fe0000>

To access all registered implementations, use the read-only ``registry`` attribute

>>> a.fun.registry.keys()
dict_keys([<class 'object'>, <class 'int'>, <class 'list'>, <class 'decimal.Decimal'>, <class 'float'>, <class 'NoneType'>])
>>> a.fun.registry[float]
<function MyClass.fun_num at 0x1035a2840>
>>> a.fun.registry[object]
<function MyClass.fun at 0x103fe0000>

Extending the dispatch table.
-----------------------------

Subclasses can extend the type registry of the function on the base class with their own overrides.
The ``SingleDispatch`` mixin class ensures that each subclass has it's own independant copy of the dispatch registry

>>> class SubClass(MyClass):
...     @MyClass.fun.register(str)
...     def fun_str(self, arg, verbose=False):
...         print('subclass')
...
>>> s = SubClass()
>>> s.fun('hello')
subclass
>>> b = MyClass()
>>> b.fun('hello')
hello

Overriding the dispatch table
-----------------------------
There are two ways to override the dispatch function for a given type.
One way is to override a base-class method that is in the base class dispatch table.
Method overrides do not need to provide the ``register`` decorator again to be used in the dispatch of ``fun``, you can
simply override the specific dispatch function you want to modify.

>>> class SubClass2(MyClass):
...     def fun_int(self, arg, verbose=False):
...         print('subclass int')
...
>>> s = SubClass2()
>>> s.fun(1)
subclass int

The other way is to register a method with an existing type using the `register` method.

>>> class SubClass3(MyClass):
...    @MyClass.fun.register(int)
...    def fun_int_override(self, arg, verbose=False):
...        print('subclass3 int')
...
>>> s = SubClass3()
>>> s.fun(1)
subclass3 int

Note that the decorator takes precedence over the method name, so if you do something like this:

>>> class SubClass4(MyClass):
...    @MyClass.fun.register(str)
...    def fun_int(self, arg, verbose=False):
...        print('silly mistake')

then SubClass4.fun_int is used for string arguments.

>>> s = SubClass4()
>>> s.fun(1)
1
>>> s.fun('a string')
silly mistake

Instance overrides
------------------

Method overrides can be specified on individual instances if necessary

>>> def fun_str(obj, arg, verbose=False):
...    print('instance str')
>>> b = MyClass()
>>> b.fun.register(str, fun_str)
<function fun_str at 0x000002376A3D32F0>
>>> b.fun('hello')
instance str
>>> b2 = MyClass()
>>> b2.fun('hello')
hello

Integration with type hints
---------------------------

For functions annotated with types, the decorator will infer the type of the first argument automatically as shown below

>>> class MyClassAnno(SingleDispatch):
...     @singledispatch
...     def fun(self, arg):
...         print('default')
...
...     @fun.register
...     def fun_int(self, arg: int):
...         print('int')
...
>>> class SubClassAnno(MyClassAnno):
...     @MyClassAnno.fun.register
...     def fun_float(self, arg: float):
...         print('float')
...
...     @MyClassAnno.fun.register
...     def fun_list(self, arg: typing.List[str]):
...         print('list')

Note that methoddispatch ignores type specialization in annotations as only the class is used for dispatching.
This means that ``fun_list`` will be called for all list instances regardless of what is in the list.

Accessing the method ``fun`` via a class will use the dispatch registry for that class

>>> SubClass2.fun(s, 1)
subclass int
>>> MyClass.fun(s, 1)
1

``super()`` also works as expected using the dispatch table of the super class.

>>> super(Mixin1, s).fun(1)
1

The usual method resolution order applies to mixin or multiple inheritance. For example:

>>> class BaseClassForMixin(SingleDispatch):
...    def __init__(self):
...        self.dispatched_by = ''
...
...    @singledispatch
...    def foo(self, bar):
...        print('BaseClass')
...        return 'default'
...
...    @foo.register(float)
...    def foo_float(self, bar):
...        print('BaseClass')
...        return 'float'
...
>>> class Mixin1(BaseClassForMixin):
...
...    @BaseClassForMixin.foo.register(int)
...    def foo_int(self, bar):
...        print('Mixin1')
...        return 'int'
...
...    @BaseClassForMixin.foo.register(str)
...    def foo_str(self, bar):
...        print('Mixin1')
...        return 'str2'
...
>>> class Mixin2(BaseClassForMixin):
...    @BaseClassForMixin.foo.register(str)
...    def foo_str2(self, bar):
...        print('Mixin2')
...        return 'str3'
...
>>> class SubClassWithMixins(Mixin2, Mixin1):
...    def foo_float(self, bar):
...        print('SubClassWithMixins')
...        return 'float'

Note that even though ``Mixin2`` has method ``foo_str2`` it will still override ``Mixin1.foo_str`` in
the dispatch of ``foo()`` because they are both handlers for the ``str`` type and Mixin2 comes before 
Mixin1 in the bases list.


>>> s = SubClassWithMixins()
>>> s.foo('text')
Mixin2
'str3'
>>> s.foo(1)
Mixin1
'int'
>>> s.foo(3.2)
SubClassWithMixins
'float'



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/seequent/methoddispatch",
    "name": "methoddispatch",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "single dispatch decorator method",
    "author": "Seequent Ltd",
    "author_email": "tim.mitchell@seequent.com",
    "download_url": "https://files.pythonhosted.org/packages/46/63/c60ffc6c28fbb8a96118cb8f8bff5892a9ff2877f7dbbd2c5d520e9441cf/methoddispatch-5.0.1.tar.gz",
    "platform": null,
    "description": "methoddispatch\r\n==============\r\n\r\n\r\nPython 3.4 added the ``singledispatch`` decorator to the ``functools`` standard library module.\r\nPython 3.8 added the ``singledispatchmethod`` decorator to the ``functools`` standard library module,\r\nhowever it does not allow sub-classes to modify the dispatch table independantly of the base class.\r\n\r\nThis library adds this functionality.\r\n\r\nTo define a generic method , decorate it with the ``@singledispatch`` decorator. Note that the dispatch happens on the type of the first argument, create your function accordingly.\r\nTo add overloaded implementations to the function, use the ``register()`` attribute of the generic function.\r\nIt is a decorator, taking a type parameter and decorating a function implementing the operation for that type.\r\nThe ``register()`` attribute returns the undecorated function which enables decorator stacking, pickling, as well as creating unit tests for each variant independently\r\n\r\n>>> from methoddispatch import singledispatch, SingleDispatch\r\n>>> from decimal import Decimal\r\n>>> class MyClass(SingleDispatch):\r\n...     @singledispatch\r\n...     def fun(self, arg, verbose=False):\r\n...         if verbose:\r\n...             print(\"Let me just say,\", end=\" \")\r\n...         print(arg)\r\n...\r\n...     @fun.register(int)\r\n...     def fun_int(self, arg, verbose=False):\r\n...         if verbose:\r\n...             print(\"Strength in numbers, eh?\", end=\" \")\r\n...         print(arg)\r\n...\r\n...     @fun.register(list)\r\n...     def fun_list(self, arg, verbose=False):\r\n...         if verbose:\r\n...             print(\"Enumerate this:\")\r\n...         for i, elem in enumerate(arg):\r\n...             print(i, elem)\r\n...\r\n...     @fun.register(float)\r\n...     @fun.register(Decimal)\r\n...     def fun_num(obj, arg, verbose=False):\r\n...         if verbose:\r\n...             print(\"Half of your number:\", end=\" \")\r\n...         print(arg / 2)\r\n\r\nThe ``register()`` method relys on ``SingleDispatch.__init_subclass__``\r\nto create the actual dispatch table rather than adding the function directly.\r\nThis also means that (unlike functools.singledispatchmethod) two methods\r\nwith the same name cannot be registered as only the last one will be in the class dictionary.\r\n\r\nFunctions not defined in the class can be registered with a generic method using the ``add_overload`` method.\r\n\r\n>>> def nothing(obj, arg, verbose=False):\r\n...    print('Nothing.')\r\n>>> MyClass.fun.add_overload(type(None), nothing)\r\n\r\nUsing ``add_overload`` will affect all instances of ``MyClass`` as if it were part of the class declaration.\r\nWhen called, the generic function dispatches on the type of the first argument\r\n\r\n>>> a = MyClass()\r\n>>> a.fun(\"Hello, world.\")\r\nHello, world.\r\n>>> a.fun(\"test.\", verbose=True)\r\nLet me just say, test.\r\n>>> a.fun(42, verbose=True)\r\nStrength in numbers, eh? 42\r\n>>> a.fun(['spam', 'spam', 'eggs', 'spam'], verbose=True)\r\nEnumerate this:\r\n0 spam\r\n1 spam\r\n2 eggs\r\n3 spam\r\n>>> a.fun(None)\r\nNothing.\r\n>>> a.fun(1.23)\r\n0.615\r\n\r\nWhere there is no registered implementation for a specific type, its method resolution order is used to find a more generic implementation.\r\nThe original function decorated with ``@singledispatch`` is registered for the base ``object`` type, which means it is used if no better implementation is found.\r\n\r\nTo check which implementation will the generic function choose for a given type, use the ``dispatch()`` method\r\n\r\n>>> a.fun.dispatch(float)\r\n<function MyClass.fun_num at 0x1035a2840>\r\n>>> a.fun.dispatch(dict)    # note: default implementation\r\n<function MyClass.fun at 0x103fe0000>\r\n\r\nTo access all registered implementations, use the read-only ``registry`` attribute\r\n\r\n>>> a.fun.registry.keys()\r\ndict_keys([<class 'object'>, <class 'int'>, <class 'list'>, <class 'decimal.Decimal'>, <class 'float'>, <class 'NoneType'>])\r\n>>> a.fun.registry[float]\r\n<function MyClass.fun_num at 0x1035a2840>\r\n>>> a.fun.registry[object]\r\n<function MyClass.fun at 0x103fe0000>\r\n\r\nExtending the dispatch table.\r\n-----------------------------\r\n\r\nSubclasses can extend the type registry of the function on the base class with their own overrides.\r\nThe ``SingleDispatch`` mixin class ensures that each subclass has it's own independant copy of the dispatch registry\r\n\r\n>>> class SubClass(MyClass):\r\n...     @MyClass.fun.register(str)\r\n...     def fun_str(self, arg, verbose=False):\r\n...         print('subclass')\r\n...\r\n>>> s = SubClass()\r\n>>> s.fun('hello')\r\nsubclass\r\n>>> b = MyClass()\r\n>>> b.fun('hello')\r\nhello\r\n\r\nOverriding the dispatch table\r\n-----------------------------\r\nThere are two ways to override the dispatch function for a given type.\r\nOne way is to override a base-class method that is in the base class dispatch table.\r\nMethod overrides do not need to provide the ``register`` decorator again to be used in the dispatch of ``fun``, you can\r\nsimply override the specific dispatch function you want to modify.\r\n\r\n>>> class SubClass2(MyClass):\r\n...     def fun_int(self, arg, verbose=False):\r\n...         print('subclass int')\r\n...\r\n>>> s = SubClass2()\r\n>>> s.fun(1)\r\nsubclass int\r\n\r\nThe other way is to register a method with an existing type using the `register` method.\r\n\r\n>>> class SubClass3(MyClass):\r\n...    @MyClass.fun.register(int)\r\n...    def fun_int_override(self, arg, verbose=False):\r\n...        print('subclass3 int')\r\n...\r\n>>> s = SubClass3()\r\n>>> s.fun(1)\r\nsubclass3 int\r\n\r\nNote that the decorator takes precedence over the method name, so if you do something like this:\r\n\r\n>>> class SubClass4(MyClass):\r\n...    @MyClass.fun.register(str)\r\n...    def fun_int(self, arg, verbose=False):\r\n...        print('silly mistake')\r\n\r\nthen SubClass4.fun_int is used for string arguments.\r\n\r\n>>> s = SubClass4()\r\n>>> s.fun(1)\r\n1\r\n>>> s.fun('a string')\r\nsilly mistake\r\n\r\nInstance overrides\r\n------------------\r\n\r\nMethod overrides can be specified on individual instances if necessary\r\n\r\n>>> def fun_str(obj, arg, verbose=False):\r\n...    print('instance str')\r\n>>> b = MyClass()\r\n>>> b.fun.register(str, fun_str)\r\n<function fun_str at 0x000002376A3D32F0>\r\n>>> b.fun('hello')\r\ninstance str\r\n>>> b2 = MyClass()\r\n>>> b2.fun('hello')\r\nhello\r\n\r\nIntegration with type hints\r\n---------------------------\r\n\r\nFor functions annotated with types, the decorator will infer the type of the first argument automatically as shown below\r\n\r\n>>> class MyClassAnno(SingleDispatch):\r\n...     @singledispatch\r\n...     def fun(self, arg):\r\n...         print('default')\r\n...\r\n...     @fun.register\r\n...     def fun_int(self, arg: int):\r\n...         print('int')\r\n...\r\n>>> class SubClassAnno(MyClassAnno):\r\n...     @MyClassAnno.fun.register\r\n...     def fun_float(self, arg: float):\r\n...         print('float')\r\n...\r\n...     @MyClassAnno.fun.register\r\n...     def fun_list(self, arg: typing.List[str]):\r\n...         print('list')\r\n\r\nNote that methoddispatch ignores type specialization in annotations as only the class is used for dispatching.\r\nThis means that ``fun_list`` will be called for all list instances regardless of what is in the list.\r\n\r\nAccessing the method ``fun`` via a class will use the dispatch registry for that class\r\n\r\n>>> SubClass2.fun(s, 1)\r\nsubclass int\r\n>>> MyClass.fun(s, 1)\r\n1\r\n\r\n``super()`` also works as expected using the dispatch table of the super class.\r\n\r\n>>> super(Mixin1, s).fun(1)\r\n1\r\n\r\nThe usual method resolution order applies to mixin or multiple inheritance. For example:\r\n\r\n>>> class BaseClassForMixin(SingleDispatch):\r\n...    def __init__(self):\r\n...        self.dispatched_by = ''\r\n...\r\n...    @singledispatch\r\n...    def foo(self, bar):\r\n...        print('BaseClass')\r\n...        return 'default'\r\n...\r\n...    @foo.register(float)\r\n...    def foo_float(self, bar):\r\n...        print('BaseClass')\r\n...        return 'float'\r\n...\r\n>>> class Mixin1(BaseClassForMixin):\r\n...\r\n...    @BaseClassForMixin.foo.register(int)\r\n...    def foo_int(self, bar):\r\n...        print('Mixin1')\r\n...        return 'int'\r\n...\r\n...    @BaseClassForMixin.foo.register(str)\r\n...    def foo_str(self, bar):\r\n...        print('Mixin1')\r\n...        return 'str2'\r\n...\r\n>>> class Mixin2(BaseClassForMixin):\r\n...    @BaseClassForMixin.foo.register(str)\r\n...    def foo_str2(self, bar):\r\n...        print('Mixin2')\r\n...        return 'str3'\r\n...\r\n>>> class SubClassWithMixins(Mixin2, Mixin1):\r\n...    def foo_float(self, bar):\r\n...        print('SubClassWithMixins')\r\n...        return 'float'\r\n\r\nNote that even though ``Mixin2`` has method ``foo_str2`` it will still override ``Mixin1.foo_str`` in\r\nthe dispatch of ``foo()`` because they are both handlers for the ``str`` type and Mixin2 comes before \r\nMixin1 in the bases list.\r\n\r\n\r\n>>> s = SubClassWithMixins()\r\n>>> s.foo('text')\r\nMixin2\r\n'str3'\r\n>>> s.foo(1)\r\nMixin1\r\n'int'\r\n>>> s.foo(3.2)\r\nSubClassWithMixins\r\n'float'\r\n\r\n\r\n",
    "bugtrack_url": null,
    "license": "BSD",
    "summary": "singledispatch decorator for class methods.",
    "version": "5.0.1",
    "project_urls": {
        "Homepage": "https://github.com/seequent/methoddispatch"
    },
    "split_keywords": [
        "single",
        "dispatch",
        "decorator",
        "method"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "7786fbf72dfa80198854c6c52d8b70e2ced8b1de6af7f56a3116b2978e69d1eb",
                "md5": "e9a907d047f7aa151f8124e176d70af1",
                "sha256": "1c43e16f4e18b31b45193f63cb2b99515f35b4ba3ad9a16611be6532cea171a1"
            },
            "downloads": -1,
            "filename": "methoddispatch-5.0.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "e9a907d047f7aa151f8124e176d70af1",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 19292,
            "upload_time": "2023-11-21T03:37:10",
            "upload_time_iso_8601": "2023-11-21T03:37:10.306559Z",
            "url": "https://files.pythonhosted.org/packages/77/86/fbf72dfa80198854c6c52d8b70e2ced8b1de6af7f56a3116b2978e69d1eb/methoddispatch-5.0.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "4663c60ffc6c28fbb8a96118cb8f8bff5892a9ff2877f7dbbd2c5d520e9441cf",
                "md5": "b4b2260db97551fe23da76d66d2e2d0f",
                "sha256": "b88b7f40665515c43101b0a9c55323b6771eab71d6ebbb5dac94d35625f1be4c"
            },
            "downloads": -1,
            "filename": "methoddispatch-5.0.1.tar.gz",
            "has_sig": false,
            "md5_digest": "b4b2260db97551fe23da76d66d2e2d0f",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 8906,
            "upload_time": "2023-11-21T03:37:12",
            "upload_time_iso_8601": "2023-11-21T03:37:12.691234Z",
            "url": "https://files.pythonhosted.org/packages/46/63/c60ffc6c28fbb8a96118cb8f8bff5892a9ff2877f7dbbd2c5d520e9441cf/methoddispatch-5.0.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-11-21 03:37:12",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "seequent",
    "github_project": "methoddispatch",
    "travis_ci": true,
    "coveralls": false,
    "github_actions": false,
    "lcname": "methoddispatch"
}
        
Elapsed time: 0.19447s