0

In python I cannot seem to overload the below functions:

#!/usr/bin/env python

import subprocess
def my_function (a) :
    subprocess.call(['proc', a])
    return;

def my_function (a, b) :
    subprocess.call(['proc','-i',a,b])
    return;

def my_function (a, b, c, d) :
    subprocess.call(['proc','-i',a,b,'-u',c,d])
    return; 

E.g. when I call with:

mymodules.my_function("a", "b")

I get:

Traceback (most recent call last):
  File "sample.py", line 11, in <module>
    mymodules.my_function("a", "b") 
TypeError: my_function() takes exactly 4 arguments (2 given)

Why does it try to call the function taking 4 arguments?

3
  • 1
    Python does not support overloading by design. Jan 24, 2018 at 20:46
  • 4
    That's not how functions work in python. They are objects, like anything else, so only one at a time can be called my_function. Jan 24, 2018 at 20:46
  • 2
    Because that's the only version that exists after defining all three, because it was defined last. It's not clear why you thought you could do this.
    – jonrsharpe
    Jan 24, 2018 at 20:46

1 Answer 1

5

Because overloading of function does not work in python as it does in other languages.

What I would do :

def my_function (a, b=None, c=None, d=None) :
    if b is None:
        subprocess.call(['proc', a])
    elif c is None:
        subprocess.call(['proc','-i',a,b])
    else:
        subprocess.call(['proc','-i',a,b,'-u',c,d])
    return; 

It will automatically detect the variables that you enter, and fill the ones you don't enter with None by default. Of course for it to work, your variables must never take the value of None

Not the answer you're looking for? Browse other questions tagged or ask your own question.