Cover Image for **args and **kwargs in Python
119 views

**args and **kwargs in Python

The Python has *args and **kwargs are special syntax used in function definitions to pass a variable number of arguments to a function. They allow you to create more flexible and generic functions that can accept different numbers of positional and keyword arguments.

  1. *args (Arbitrary Positional Arguments):
  • The *args parameter in a function definition allows you to pass a variable number of positional arguments.
  • It collects all extra positional arguments into a tuple.
  • You can use any name for *args, but *args is a widely recognized convention. Example:
Python
 def my_function(arg1, *args):
     print(f"arg1: {arg1}")
     print(f"args: {args}")

 my_function(1, 2, 3, 4)
 # Output:
 # arg1: 1
 # args: (2, 3, 4)
  1. **kwargs (Arbitrary Keyword Arguments):
  • The **kwargs parameter in a function definition allows you to pass a variable number of keyword arguments.
  • It collects all extra keyword arguments into a dictionary.
  • You can use any name for **kwargs, but **kwargs is a widely recognized convention. Example:
Python
 def my_function(arg1, **kwargs):
     print(f"arg1: {arg1}")
     print(f"kwargs: {kwargs}")

 my_function(1, name="John", age=30)
 # Output:
 # arg1: 1
 # kwargs: {'name': 'John', 'age': 30}
  1. Using Both *args and **kwargs: You can use both *args and **kwargs in the same function definition, but *args must appear before **kwargs.
Python
 def my_function(arg1, *args, **kwargs):
     print(f"arg1: {arg1}")
     print(f"args: {args}")
     print(f"kwargs: {kwargs}")

 my_function(1, 2, 3, name="John", age=30)
 # Output:
 # arg1: 1
 # args: (2, 3)
 # kwargs: {'name': 'John', 'age': 30}

These constructs are useful when you want to create functions that are more flexible and can accept various types and numbers of arguments. They are commonly used in libraries and frameworks to provide generic functions that work with different input data.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS