[Python-ideas] Make functools.singledispatch register method return original function.

Thomas Jollans tjol at tjol.eu
Sat Jun 17 17:42:01 EDT 2017


On 17/06/17 23:27, Mital Ashok via Python-ideas wrote:
> [snip]
> So I'm suggesting that @function.register for single dispatch
> functions returns the same function, so you would end up with
> something like:
>
> @singledispatch
> def fun(arg, verbose=True):
>     if verbose:
>         print("Let me just say,", end=" ")
>     print(arg)
>
> @fun.register(int)
> def fun(arg, verbose=True):
>     if verbose:
>         print("Strength in numbers, eh?", end=" ")
>     print(arg)
In principle, I like it! However...
>
> And to get back the old behaviour, where you can get the function
> being decorated, just call it afterwards:

A backwards incompatible change like this is not going to happen.

In actual fact, a couple of uses of the current behaviour are in the
docs at
https://docs.python.org/3/library/functools.html#functools.singledispatch :

> The register() attribute returns the undecorated function which
> enables decorator stacking, pickling, as well as creating unit tests
> for each variant independently:
>
> >>>
> >>> @fun.register(float)
> ... @fun.register(Decimal)
> ... def fun_num(arg, verbose=False):
> ...     if verbose:
> ...         print("Half of your number:", end=" ")
> ...     print(arg / 2)
> ...
> >>> fun_num is fun
> False

Perhaps it makes sense to add a new method to singledispatch that has
the behaviour you're suggesting, just with a different name?

-- Thomas



More information about the Python-ideas mailing list