Sean
Sean

Reputation: 1313

How to use a non-keyword arg after a keyword arg in a method call?

So I have a function defined as such:

def getDistnace(self, strings, parentD, nodeName, nodeDistance):

And I am calling it with:

Node.getDistnace(newNode, strings, parentD, nodeName=None, nodeDistance=None)

and

Node.getDistnace(node, strings=None, parentD=None, nodeName, nodeDistance)

Which are both from 2 other different functions. But my problem is that I get an error stating there is a non-keyword arg after keyword arg.

Is there any way around this error? The first Node.getDistnace adds strings and parentD to getDistance, and the second Node.getDistnace adds nodeName and nodeDistance to the function.

Upvotes: 2

Views: 6520

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123810

All your arguments are positional, you don't need to use keywords at all:

Node.getDistnace(newNode, strings, parentD, None, None)

Node.getDistnace(node, None, None, nodeName, nodeDistance)

I think you are confusing local variables (what you pass into the function) and the argument names of the function. They happen to match in your code, but there is no requirement that they do match.

The following code would have the same effect as your first example:

arg1, arg2, arg3 = newNode, strings, parentD
Node.getDistnace(arg1, arg2, arg3, None, None)

If you do want to use keyword arguments, that's fine, but they cannot be followed by positional arguments. You can then alter the ordering and python will still match them up:

Node.getDistnace(node, nodeDistance=nodeDistance, strings=None, parentD=None, nodeName=nodeName)

Here I moved nodeDistance to the front of the keyword arguments, but Python will still match it to the last argument of the getDistnace method.

Upvotes: 7

Related Questions