Default Arguments, Keyword Arguments & *args/**kwargs
You'll learn to
- -Give parameters default values and call functions with keyword arguments
- -Recognize and avoid the mutable-default-argument bug
- -Write functions that accept a variable number of arguments with `*args` and `**kwargs`
Real functions are rarely called with a single fixed set of arguments every time. Python gives you three complementary tools for flexibility: default values for parameters that are usually the same, keyword arguments for calling functions in a self-documenting way, and `*args`/`**kwargs` for functions that accept an arbitrary number of inputs.
Default Arguments
A parameter can be given a default value in the `def` line. If the caller does not supply that argument, the default is used.
The Mutable Default Argument Trap
Here is one of the most notorious gotchas in the entire language. Default argument values are evaluated exactly once, when the function is defined, not once per call. If you use a mutable object (a list, dict, or set) as a default, every call that relies on the default shares the same object.
The fix is a well-known idiom: default the parameter to `None`, then create a fresh mutable object inside the function body when the caller did not supply one.
Never use a list, dict, or set literal directly as a default parameter value unless you specifically want every call to share the same object. Default to `None` and build the mutable object inside the function instead.
Keyword Arguments
Any argument can be passed by name instead of by position, which makes call sites self-documenting and lets you skip arguments that have defaults without worrying about order.
*args and **kwargs
Sometimes you do not know in advance how many arguments a function will receive. `*args` collects any extra positional arguments into a tuple. `**kwargs` collects any extra keyword arguments into a dict.
- -`*args` and `**kwargs` are just conventional names. The `*` and `**` are what matter, not the word "args".
- -Order in a function signature is always: required positional params, then `*args`, then keyword-only/default params, then `**kwargs`.
- -You will see `*args, **kwargs` again when wrapping functions with decorators later in this course. It is exactly how a generic wrapper forwards whatever was passed in to the original function.
Interview Signal is part of Pro
See a real weak answer next to a real strong one for this exact topic.
Quiz is part of Pro
Test what you just read with a short quiz, and bank the XP.