Functions with Optional Arguments
Explore how to define Python functions that accept optional arguments using *args for positional and **kwargs for keyword arguments. Understand how these features enhance function flexibility and make your code more adaptable to different input scenarios.
We'll cover the following...
This section brings detailed information about an eminently used feature in Python programming. Getting a firm hold on this concept will make you a competent developer, as it brings wonders.
The *args and **kwargs parameters
The args and kwargs parameters allow a function to accept optional arguments.
- The keyword
argsmeans positional arguments. - The keyword
kwargsmeans keyword arguments.
Let’s see a simple example to get a basic understanding of these parameters.
In the code above, we define a function func at line 1. It takes one required argument: fixed. If func doesn’t get the required argument, it will generate an error. The next two parameters are optional arguments. The *args will collect all positional arguments in the form of a tuple. Whereas, **kwargs will collect all keyword arguments as a dictionary. Then we are printing all the arguments one by one. We are validating the existence of positional and keyword arguments with if structure (at line 3 and line 5 respectively). Now, we start calling func in different ways:
- Look at line 8. We are calling
funcwith one argument: Educative. Without any doubt, it will be assigned tofixedargument. The functionfuncwill only print Educative becauseargsandkwargsare not present. - Look at line 10. We are calling
funcwith four arguments: Educative, 1, 2, and 3. Here, Educative will be assigned tofixedargument. However, 1, 2, and 3 will be retrieved as a tuple by*args. The functionfuncwill print:- Educative
- (1, 2, 3)
- Look at line 12. We are calling
funcwith six arguments: Educative, 1, 2, 3, level=‘advanced’, and language=‘Python3’. Here, Educative will be assigned tofixedargument. However, 1, 2, and 3 will be retrieved as a tuple by*args. Whereas, level=‘advanced’, and language=‘Python3’ will be retrieved as a dictionary by**kwargs. The functionfuncwill print:- Educative
- (1, 2, 3)
- {‘language’: ‘Python3’, ‘level’: ‘advanced’}
⚙️ Note: The actual syntax is
*and**. Calling themargsandkwargsis just a convention.