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

Nick Coghlan ncoghlan at gmail.com
Sat Jun 17 22:24:21 EDT 2017


On 18 June 2017 at 07:27, Mital Ashok via Python-ideas
<python-ideas at python.org> wrote:
> Right now, an example for single dispatch would be:
>
> from functools import singledispatch
>
> @singledispatch
> def fun(arg, verbose=True):
>     if verbose:
>         print("Let me just say,", end=" ")
>     print(arg)
>
> @fun.register(int)
> def _(arg, verbose=True):
>     if verbose:
>         print("Strength in numbers, eh?", end=" ")
>     print(arg)
>
> @fun.register(list)
> def _(arg, verbose=True):
>     if verbose:
>         print("Enumerate this:")
>     for i, elem in enumerate(arg):
>         print(i, elem)
>
> But this makes a useless _ function, that should either be deleted or
> ignored.

Don't do that, give the overloads meaningful names that your test
suite can then use to check that they do the right thing independently
of the dispatch process.

Even if you're not doing unit testing at that level, the names will
also show up in exception tracebacks and other forms of introspection
(e.g. process state dumps), and seeing descriptive names like
"_fun_for_int" and "_fun_for_list" is *significantly* more informative
than seeing multiple distinct functions all called "_" or "__".

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list