Singledispatch decorator doesn't work as advertised

875 Views Asked by At

I am testing python's singledispatch: https://docs.python.org/3/library/functools.html?highlight=singledispatch#functools.singledispatch

Block A is supposed to work as well as Block B according to the document. However, you can see in the output that only Block B works as expected.

What is the problem here? Thanks.

from functools import singledispatch


# Block A
@singledispatch
def divider(a, b=1):
    print(a, b)

@divider.register
def _(a: int, b=1):
    print(a/b)

@divider.register
def _(a: str, b=1):
    print(a[:len(a)//b])

divider(25, 2)
divider('single dispatch practice', 2)


# Block B
@singledispatch
def div(a, b=1):
    print(a, b)


@div.register(int)
def _(a: int, b=1):
    print(a/b)


@div.register(str)
def _(a: str, b=1):
    print(a[:len(a)//b])

div(25 , 2)
div('single dispatch practice', 2)

Output:

>> 25 2
>> single dispatch practice 2
>> 12.5
>> single dispatch
1

There are 1 best solutions below

0
On

I am testing python's singledispatch (...) What's is the problem here?

You are correct to use type annotations, however @singledispatch only uses them since Python 3.7 (annotations were introduced in Python 3.0, singledispatch in 3.4). Thus

# works since 3.4
@foo.register(str)
def foo_str(a: str):
    ...

# works since 3.7
@foo.register
def foo_str(a: str)
    ...