Core Module
12 min forge
Python Functions: *args and **kwargs
Deep dive into Python's dynamic argument handling and the power of flexible function signatures.
Python Functions: *args and **kwargs
π‘οΈ What are dynamic arguments?
In Python, you can define functions that accept a variable number of arguments using *args (positional) and **kwargs (keyword). These allow for highly flexible APIs often seen in libraries like Django or Flask.
β° When to Use
- Wrappers/Decorators: When you don't know in advance what arguments the original function will take.
- Subclassing: When overriding a method but still wanting to pass "the rest" of the arguments to
super(). - Generic APIs: Creating utility functions that act on varying inputs.
π Complexity & Performance
- Packing/Unpacking: Positional arguments (
*args) are packed into atuple. Keyword arguments (**kwargs) are packed into adict. - Overhead: Accessing
kwargsis slightly slower than accessing named parameters because it involves a dictionary lookup, though this is negligible for most applications.
π» Code Example: The Ultimate Flex Function
python Standarddef master_function(fixed_arg, *args, **kwargs): print(f"Fixed: {fixed_arg}") # args is a tuple if args: print(f"Positional extras: {args}") # kwargs is a dict if kwargs: print(f"Keyword extras: {kwargs}") # Usage master_function("Hello", 1, 2, 3, status="active", debug=True) # Unpacking pattern data = [1, 2, 3] config = {"timeout": 30, "retries": 3} # Pass list elements as positional and dict as keywords master_function("API Call", *data, **config)
β οΈ Interview Pitfalls
- Argument Order: The order must always be:
(fixed, *args, **kwargs). Violating this results in aSyntaxError. - Mutable Defaults: Never do
def func(x=[]). The list is created once at definition time and shared across all calls. Usedef func(x=None)and initialize inside. - Keyword-Only Arguments: Mention that everything after
*args(or just a bare*) MUST be passed as a keyword. This is great for making APIs explicit. - Scope (LEGB): Understand how Python resolves variables: Local -> Enclosing -> Global -> Built-in.