Python keyword args vs kwargs
This might be a simple question:
Is there any difference between the two folowing:
def myfunc(a_list = [开发者_StackOverflow中文版], **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
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!
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".
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.
精彩评论