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 a tuple. Keyword arguments (**kwargs) are packed into a dict.
  • Overhead: Accessing kwargs is 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 Standard
def 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

  1. Argument Order: The order must always be: (fixed, *args, **kwargs). Violating this results in a SyntaxError.
  2. Mutable Defaults: Never do def func(x=[]). The list is created once at definition time and shared across all calls. Use def func(x=None) and initialize inside.
  3. 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.
  4. Scope (LEGB): Understand how Python resolves variables: Local -> Enclosing -> Global -> Built-in.