2

This might be a simple question:

Is there any difference between the two folowing:

def myfunc(a_list = [], **kwargs):
    my_arg = kwargs.get('my_arg', None)
    pass

and

def myfucn(a_list = [], my_arg = None):
    pass

If not, which would be considered more pythonic?

Thanks, -Matt

Matty P
  • 100
  • 5
  • 3
    More importantly, never use a mutable default argument (a_list above). See here for details: http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument – Ryan Bright Apr 14 '11 at 18:35
  • 1
    Sidnote: Do not use `[]` as a default argument, as `[]` is mutable. http://google-styleguide.googlecode.com/svn/trunk/pyguide.html#Default_Argument_Values – wkl Apr 14 '11 at 18:36

3 Answers3

7

For a simple function, it's more Pythonic to explicitly define your arguments. Unless you have a legit requirement to accept any number of unknown or variable arguments, the **kwargs method is adding unnecessary complexity.

Bonus: Never initialize a list in the function definition! This can have unexpected results by causing it to persist because lists are mutable!

jathanism
  • 33,067
  • 9
  • 68
  • 86
1

The first one can take virtually any keyword arguments provided (regardless of the fact that it only uses one of them), whereas the second can only take two. Neither is more Pythonic, you simply use the one appropriate for the task.

Also, the second is not "keyword arguments" but rather a "default value".

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

The second alternative allows my_arg to be passed as a positional rather than a keyword argument. I would consider it unpythonic to declare **kwargs when you don't actually use them for anything.

sverre
  • 6,768
  • 2
  • 27
  • 35