Esteemator
Esteemator

Reputation: 107

Are there any dangers associated with using kwarg=kwarg in Python functions?

I've sometimes seen code with kwarg=kwarg in one of the functions as shown below:

def func1(foo, kwarg):
    return(foo+kwarg)
def func2(bar, kwarg):
    return(func1(bar*2, kwarg=kwarg))

print(func2(4,5))

I've normally tried to avoid this notation (e.g. by using kwarg1=kwarg2) in order to avoid any possible bugs, but is this actually necessary?

Upvotes: 0

Views: 135

Answers (1)

Jeff
Jeff

Reputation: 2238

There's nothing wrong with it - in this case kwarg is just a variable name - it's not reserved. There may be a bit of confusion with it though, since def func(**kwargs): is the common syntax for creating a dictionary of all the "key word arguments" that are passed into the function. Since you're not doing that here, using such a similar name is unnecessarily confusing. Although it's not clear you're talking about using that exact name, so maybe this is just an issue with the example.

But broadly speaking, passing something=something is fairly common practice. You'll see it in lots of places, for example if you're iterating through a color pallette in Matplotlib, you might pass color=color into plot, or if you're building a list of headers in Pandas you might pass coloumns=columns into DataFrame.

Bottom line is it should be clear. If it is, it's good. If it's not, it isn't.

Upvotes: 2

Related Questions