pass kwargs argument to another function with kwargs
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
In Python, **kwargs collects keyword arguments into a dictionary. To pass these arguments to another function, use the ** unpacking operator: other_function(**kwargs). This forwards all keyword arguments to the called function as if they were specified individually. This pattern is fundamental in Python for creating wrapper functions, decorators, and class hierarchies where functions need to accept and pass through arbitrary keyword arguments.
Basic Forwarding
**kwargs in the outer function collects name, age, and city into a dict {'name': 'Alice', 'age': 30, 'city': 'Seattle'}. Then **kwargs unpacks the dict back into keyword arguments for inner_function.
Adding or Modifying Arguments
kwargs.setdefault(key, value) adds the key only if it is not already present, allowing callers to override defaults.
Combining *args and **kwargs
*args collects positional arguments as a tuple. **kwargs collects keyword arguments as a dict. Together they capture the entire call signature.
Decorator Pattern
Decorators use *args, **kwargs to make the wrapper transparent — it accepts and forwards any combination of arguments the original function expects.
Class Inheritance with super()
Each class in the hierarchy consumes the kwargs it needs and forwards the rest via super().__init__(**kwargs). This is the cooperative multiple inheritance pattern.
Filtering kwargs Before Forwarding
Use inspect.signature to find which parameters a function accepts, then filter kwargs to avoid TypeError: unexpected keyword argument.
Merging Multiple kwargs Sources
The {**a, **b} syntax merges two dicts, with the second overriding duplicate keys.
Common Pitfalls
- Forgetting the
**when forwarding: Writingother_func(kwargs)passes the entire dict as a single positional argument. You must useother_func(**kwargs)to unpack it into keyword arguments. - Modifying kwargs and causing duplicate keyword arguments: If you do
other_func(name="Alice", **kwargs)and kwargs also containsname, Python raisesTypeError: got multiple values for argument 'name'. Remove the key from kwargs first withkwargs.pop('name', None). - Not using
functools.wrapsin decorators: Without@functools.wraps(func), the wrapper function loses the original function's name, docstring, and signature. Always applywrapsin decorator patterns. - Passing kwargs to functions that do not accept
**kwargs: If the target function has fixed parameters and kwargs contains extra keys, Python raisesTypeError: unexpected keyword argument. Filter kwargs first or ensure the target function accepts**kwargs. - Mutating the kwargs dict unintentionally:
kwargs.pop()orkwargs['key'] = valuemodifies the dict in place. If the caller expects kwargs to be unchanged, create a copy first:local_kwargs = {**kwargs}.
Summary
- Use
**kwargsto collect keyword arguments into a dict and**kwargsagain to unpack them when calling another function - This pattern is essential for decorators, wrapper functions, and cooperative inheritance with
super() - Use
kwargs.setdefault()to add default values without overriding caller-specified arguments - Filter kwargs with
inspect.signaturewhen the target function does not accept arbitrary keyword arguments - Merge multiple sources with
{**defaults, **kwargs}— later dicts override earlier ones - Always use
functools.wrapsin decorators to preserve the wrapped function's metadata
Related reading
- Passing a dictionary to a function as keyword parameters
- Passing functions with arguments to another function in Python?
- Passing HTML to template using Flask/Jinja2
- passing supplementary parameters to hyperopt objective function
- PATH issue with pytest 'ImportError No module named ...
- pdb cannot break in another thread?
- Peak-finding algorithm for Python/SciPy
- Perform commands over ssh with Python
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.