Python: **Kwargs and *Args

Outside of beings incredibly fun to say, Kwargs and Args can be pretty useful.

Here is how they work. Let us say you wanted to make a function that adds 4 numbers:

Notice what happens when we only provide 3 arguments, we error out. The same thing happens if we try to give the function 5 arguments.

pythonkwa

Well, if the world perfectly predictable, this wouldn’t be an issue. But in the real world, making a function that adds 4 and only 4 numbers isn’t very useful. A function that can add any given set of numbers however is very useful.

*args

*args to the rescue

Using the keyword *args inside the function parenthesis gives you the flexibility of having as many, or as few arguments as you want.

pythonkwa1.jpg

**kwargs

Kwargs are basically args with keywords. Think dictionaries.

pythonkwa2

You can combine regular arguments with *args and **kwargs

pythonkwa3

You can call functions with *args and **kwargs

oh, in case I forgot to mention earlier arg and kwarg are not required as keywords. As you can see in the examples below, it is the * or ** you need.

pythonkwa4.jpg


If you enjoyed this lesson, click LIKE below, or even better, leave me a COMMENT. 

Follow this link for more Python content: Python

 

Please Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s