Python *args and **kwargs

*args and **kwargs

*args and **kwargs are special syntaxes in Python used in function definitions to pass a variable number of arguments. The terms "args" and "kwargs" are conventions, and what's important is the use of the * and ** prefixes.

*args

*args allows you to pass a variable number of positional arguments.

Usage:
When you're not sure how many arguments might be passed to your function, you can use *args as a way to capture them all.

def function_with_args(*args): for arg in args: print(arg) function_with_args(1, 2, 3, 4) # Prints 1, 2, 3, 4 on separate lines 

Internals:
Internally, *args collects the extra positional arguments into a tuple.

**kwargs

**kwargs allows you to handle an undefined number of keyword arguments.

Usage:
When you're not sure how many keyword arguments might be passed to your function, or if you want to capture all keyword arguments not otherwise matched, you can use **kwargs.

def function_with_kwargs(**kwargs): for key, value in kwargs.items(): print(key, value) function_with_kwargs(name="Alice", age=25) # Prints name Alice and age 25 on separate lines 

Internals:
Internally, **kwargs collects the extra keyword arguments into a dictionary.

Combined Use:

You can use both *args and **kwargs in the same function definition, but *args has to appear before **kwargs.

def combined_example(x, y, *args, **kwargs): print(x, y) print(args) print(kwargs) combined_example(1, 2, 3, 4, 5, a=6, b=7) 

Output:

1 2 (3, 4, 5) {'a': 6, 'b': 7} 

Practical Applications:

  • Wrapper functions:
    When wrapping or decorating a function and you want to maintain the flexibility of the original function's arguments.
def my_decorator(func): def wrapper(*args, **kwargs): print("Before function call") result = func(*args, **kwargs) print("After function call") return result return wrapper @my_decorator def greet(name): print(f"Hello, {name}!") greet(name="Alice") 
  • Extending a class method: When overriding methods in subclasses, you might want to capture all the original arguments so you can pass them to the superclass method.
class Parent: def method(self, x, y): pass class Child(Parent): def method(self, *args, **kwargs): # Do something extra super().method(*args, **kwargs) 

In conclusion, *args and **kwargs provide flexibility in function definitions and allow you to handle a varying number of input arguments, which can be especially helpful in scenarios like creating decorators, wrappers, and method overrides.


More Tags

aspose rake broadcastreceiver appsettings client-side-validation google-pay fragment gsutil drop cqlsh

More Programming Guides

Other Guides

More Programming Examples