Skip to content

Instantly share code, notes, and snippets.

@mizhi
Last active January 31, 2025 04:04
Show Gist options
  • Select an option

  • Save mizhi/7bf4771fbc562966f6c0d5b2724ff438 to your computer and use it in GitHub Desktop.

Select an option

Save mizhi/7bf4771fbc562966f6c0d5b2724ff438 to your computer and use it in GitHub Desktop.
singledispatchmethod on __init__

I've been doing a bit of refresher on Python, learning about the new capabilities added in Python 3.

Tonight, I learned about @singledispatchmethod alongside typehinting.

You can use it wth __init__ on classes. Honestly, there's no reason why that shouldn't be the case since object allocation and initialization are separated in Python. But it's still nice to confirm.

from functools import *

class Foo:
    @singledispatchmethod
    def __init__(self, arg):
        raise NotImplementedError(f"Cannot initialize from {arg}")

    @__init__.register
    def _(self, a: int):
        print(f"{a} is an integer")

    @__init__.register
    def _(self, a: str):
        print(f"{a} is an string")

>>> f = Foo("asdf")
asdf is an string

>>> f2 = Foo(123)
1 is an integer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment