[Python] Why does overloading __new__ with singledispatchmethod not differentiate by type and...

Discussão em 'Python' iniciado por Stack, Maio 24, 2025.

  1. Stack

    Stack Membro Participativo

    I want my __new__ method to behave differently in some cases and wanted to split it into overloaded functions with singledispatchmethod.
    For other methods it works like expected. However for __new__ it does not work, the overloading functions are never called. What is the reason for that?

    from functools import singledispatchmethod

    class Foo:
    @singledispatchmethod
    def __new__(cls, arg1, **kwargs):
    return "default call"

    @__new__.register(int)
    def _(cls, arg1, **kwargs):
    return "called with int " + str(arg1)

    print(Foo("hi"))
    # default call
    print(Foo(1))
    # default call


    As an experiment also used singledispatch instead but without success.

    Continue reading...

Compartilhe esta Página