Frage

Our tool has python embedded. We defined a function which takes 'two' arguments (but only one user argument):

def code(self, device):
        return tools.code(self, device)

Everything works well when they actually call the function with one argument:

code(device)

The problem arises when a user makes a call without any arguments at all eg:

code()

Now the error message returned by the python interpreter is:

TypeError: code() takes exactly 2 arguments (1 given)

Now the user thinks there should be 2 arguments, when in fact they only need to provide one - is there a way to improve this error message?

War es hilfreich?

Lösung

To elaborate on my comment..

If you're calling the method, self is implicit. That counts as one argument. And you have another parameter named device. That is the other argument, hence it expects two arguments. If at some point you want to accept no arguments aside from the implicit self argument, you can use *args like this:

def code(self, *args):

Or you can use a default value for the parameter like this:

def code(self, device=''):
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top