Comment

Comment by Xophmeister

This got missed from the release announcement, but now there's `functools.singledispatchmethod`,[1] as the class method sibling to `functools.singledispatch`.[2] This allows you to overload the implementation of a function (and now a method) based on the type of its first argument. This saves you writing code like:

    def foo(bar):
        if isinstance(bar, Quux):
            # Treat bar as a Quux

        elif isinstance(bar, Xyzzy):
            # Treat bar as an Xyzzy

        # etc.
I understand runtime type checking like that is considered a bit of a Python antipattern. With `singledispatch`, you can do this instead:

    @singledispatch
    def foo(bar:Quux):
        # Quux implementation

    @foo.register
    def _(bar:Xyzzy):
        # Xyzzy implementation
With `singledispatchmethod`, you can now also do this to class methods, where the type of the first non-self/class is used by the interpreter to check the type, based on its annotation (or using the argument to its `register` method). You could mimic this behaviour using `singledispatch` in your constructor, but this syntax is much nicer.

[1] https://docs.python.org/3/library/functools.html#functools.s...

[2] https://docs.python.org/3/library/functools.html#functools.s...

parent Xophmeister 7 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton