0

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?

Esteemator
  • 107
  • 7
  • Usually you see `**kwargs`. Also, returns don't need parentheses – OneCricketeer Aug 01 '16 at 23:43
  • 1
    What specific aspect of this code are you thinking might be dangerous? There's nothing wrong with using the same name for the parameter and the value you're passing, if that's what you're worried about. – user2357112 Aug 01 '16 at 23:44
  • @user2357112 I just thought the notation looked a bit odd. Obviously I'm not expecting issues with the simple example above, but I was wondering if the above notation could cause issues when the code becomes more complex. – Esteemator Aug 01 '16 at 23:47
  • What would be a "more complex" example of `kwarg=kwarg`? The biggest problem I see here is naming a simple variable `kwarg`, which is ridiculous. A name like that should be reserved for the **kwargs syntax. – Paul Cornelius Aug 02 '16 at 00:14

1 Answers1

2

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.

Jeff
  • 2,158
  • 1
  • 16
  • 29