What is the benefit of using **kwargs over *args?

I was looking at this code from this module: https://www.codecademy.com/courses/learn-python-3/lessons/learn-python-function-arguments/exercises/keyword-argument-unpacking

from products import create_product

# Update create_products() to take arbitrary keyword arguments
def create_products(**products_dict):
  for name, price in products_dict.items():
    create_product(name, price)

# Checkpoint 3
# Update the call to `create_products()` to pass in this dictionary as a series of keywor
create_products(Baseball=3,Shirt=14,Guitar=70)

But this can be easily recreated like this:

from products import create_product

# Update create_products() to take arbitrary keyword arguments
def create_products(*products_list):
  for lists in products_list:
    for list in lists:
      create_product(list[0], list[-1])
# Checkpoint 3
# Update the call to `create_products()` to pass in this dictionary as a series of keywords
create_products([['Baseball',3],['Shirt',14],['Guitar',70]])
2 Likes

Hello!
From seeing your code, it seems that the first snippet will be faster, as you only have one for loop. The more you can reduce iterating through an object, the faster the code (generally). Here is also a good article on this subject.

3 Likes

More like, is there any real benefit in having faster running code? When I ran the two the difference in run time didn’t seem large, and didn’t really slow me down or anything.

For that specific example I’d just avoid nesting loops in general. They’re harder to read and they already run slowly in Python. You won’t notice it for short examples but it will affect you more if you have a function that’s called several thousand times (which is already slow) and it’s a bad habit to get into.

As for *args or **kwargs it depends a lot on style and readability. A fair number of functions that allow excess arguments through unpacking usually allow for both *args and **kwargs. If you need to use relevant keys/names as well as the values in your function then **kwargs would be the obvious choice but with both available you can pass whatever is easiest without repackaging your inputs to suit the function.

2 Likes

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.