开发者

Python keyword args vs kwargs

开发者 https://www.devze.com 2023-02-26 05:23 出处:网络
This might be a simple question: Is there any difference between the two folowing: def myfunc(a_list = [开发者_StackOverflow中文版], **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.

0

精彩评论

暂无评论...
验证码 换一张
取 消