Is it possible to use multiple dispatch without knowing the type?

163 Views Asked by At

Using multiple dispatch to allow for function overloading within OOP, is it possible for me to run the following code:

@dispatch(int)
  def __init__(self, radius: int):

However, remove the int, as the attribute being passed in could either be an int or a str.

1

There are 1 best solutions below

0
On

Use the functools.singledispatchmethod to overload a class method by its arguments' annotation.

from functools import singledispatchmethod


class Generic:
    """
    >>> _ = Generic(1)
    __init__ got int
    >>> _ = Generic(1.0)
    __init__ got float
    >>> _ = Generic(None)
    default __init__
    """

    @singledispatchmethod
    def __init__(self, radius):
        print("default __init__")

    @__init__.register
    def _(self, radius: int):
        print("__init__ got int")

    @__init__.register
    def _(self, radius: float):
        print("__init__ got float")