Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python keyword args vs kwargs

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

like image 254
Matty P Avatar asked Jul 10 '26 16:07

Matty P


2 Answers

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!

like image 126
jathanism Avatar answered Jul 12 '26 07:07

jathanism


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".

like image 41
Ignacio Vazquez-Abrams Avatar answered Jul 12 '26 05:07

Ignacio Vazquez-Abrams