pythonfunctionmultiple-dispatch

Simple way to do multiple dispatch in python? (No external libraries or class building?)


I'm writing a throwaway script to compute some analytical solutions to a few simulations I'm running.

I would like to implement a function in a way that, based on its inputs, will compute the right answer. So for instance, say I have the following math equation:

tmax = (s1 - s2) / 2 = q * (a^2 / (a^2 - b^2))

It seems simple to me that I should be able to do something like:

def tmax(s1, s2):
    return (s1 - s2) / 2

def tmax(a, b, q):
    return q * (a**2 / (a**2 - b**2))

I may have gotten to used to writing in julia, but I really don't want to complicate this script more than I need to.


Solution

  • In statically typed languages like C++, you can overload functions based on the input parameter types (and quantity) but that's not really possible in Python. There can only be one function of any given name.

    What you can do is to use the default argument feature to select one of two pathways within that function, something like:

    def tmax(p1, p2, p3 = None):
        # Two-argument variant has p3 as None.
    
        if p3 is None:
            return (p1 - p2) / 2
    
        # Otherwise, we have three arguments.
    
        return (p1 * p1 / (p1 * p1 - p2 * p2)) * p3
    

    If you're wondering why I've change the squaring operations from n ** 2 to n * n, it's because the latter is faster (or it was, at some point in the past, at least for small integral powers like 2 - this is probably still the case but you may want to confirm).

    A possible case where it may be faster to do g1 ** 2 rather than g1 * g1 is where g1 is a global rather than a local (it takes longer for the Python VM to LOAD_GLOBAL rather than LOAD_FAST). This is not the case with the code posted since the argument is inherently non-global.