[Python] Decorator for overloading in Python

Discussão em 'Python' iniciado por Stack, Julho 1, 2025.

  1. Stack

    Stack Membro Participativo

    I know it's not Pythonic to write functions that care about the type of the arguments, but there are cases when it's simply impossible to ignore types because they are handled differently.

    Having a bunch of isinstance checks in your function is just ugly; is there any function decorator available that enables function overloads? Something like this:

    @overload(str)
    def func(val):
    print('This is a string')

    @overload(int)
    def func(val):
    print('This is an int')


    Update:

    Here's some comments I left on David Zaslavsky's answer:


    With a few modification, this will suit my purposes pretty well. One other limitation I noticed in your implementation, since you use func.__name__ as the dictionary key, you are prone to name collisions between modules, which is not always desirable. [cont'd]

    [cont.] For example, if I have one module that overloads func, and another completely unrelated module that also overloads func, these overloads will collide because the function dispatch dict is global. That dict should be made local to the module, somehow. And not only that, it should also support some kind of 'inheritance'. [cont'd]

    [cont.] By 'inheritance' I mean this: say I have a module first with some overloads. Then two more modules that are unrelated but each import first; both of these modules add new overloads to the already existing ones that they just imported. These two modules should be able to use the overloads in first, but the new ones that they just added should not collide with each other between modules. (This is actually pretty hard to do right, now that I think about it.)
    ​


    Some of these problems could possibly be solved by changing the decorator syntax a little bit:

    first.py

    @overload(str, str)
    def concatenate(a, b):
    return a + b

    @concatenate.overload(int, int)
    def concatenate(a, b):
    return str(a) + str(b)


    second.py

    from first import concatenate

    @concatenate.overload(float, str)
    def concatenate(a, b):
    return str(a) + b

    Continue reading...

Compartilhe esta Página