Sub topic 9
Common pitfalls and errors
This chapter assumes you can define functions with *args and **kwargs, unpack with * and ** at call sites, and know the required parameter order. Here you will learn to recognize the errors these features produce and how to fix them.
Error quick reference
| Error message (shortened) | Usual cause | Fix |
|---|---|---|
| `got multiple values for argument 'x'` | A value was given both positionally and through `**` | Remove one source |
| `got multiple values for keyword argument 'x'` | Two `**` mappings in one call share a key | Merge into one dict first |
| `unsupported operand type(s)` inside the function | A list was passed without `*` | Add `*` at the call |
| `unexpected keyword argument 'x'` | A key in `**` has no matching parameter | Check the spelling or add a parameter |
| `SyntaxError` at `def` | Parameters are in the wrong order | Follow the standard order |
Duplicate values for one parameter
A call can fill a parameter only once. If a positional argument already fills name, a ** mapping that also contains name is an error.
def greet(name):
return f"Hello, {name}"
data = {"name": "Bob"}
try:
greet("Ada", **data)
except TypeError as error:
print(error) # greet() got multiple values for argument 'name'The same rule applies when two mappings are unpacked into one call. In a dict literal the later key silently wins, but in a call it is an error.
def build(size, **options):
return size, options
base = {"color": "red"}
extra = {"color": "blue"}
print({**base, **extra}) # {'color': 'blue'}
try:
build(1, **base, **extra)
except TypeError as error:
print(error) # build() got multiple values for keyword argument 'color'To get "later wins" behavior in a call, merge first: build(1, **{**base, **extra}).
Forgetting the star at the call site
A function declared with *args accepts any number of arguments. A list passed without * is just one argument.
def total(*args):
return sum(args)
numbers = [1, 2, 3]
try:
total(numbers)
except TypeError as error:
print(error) # unsupported operand type(s) for +: 'int' and 'list'
print(total(*numbers)) # 6Here args is ([1, 2, 3],), a tuple holding one list. sum then tries 0 + [1, 2, 3]. The error appears inside the function, so check the call site first.
Related rules: * needs an iterable and ** needs a mapping with string keys. Unpacking 5 with *, or {1: "a"} with **, raises a TypeError. Also, * consumes an iterator. After f(*iterator) the iterator is exhausted.
Typos disappear into `**kwargs`
A function that accepts **kwargs accepts any keyword name, including misspelled ones. The wrong name lands in the dictionary and your code never reads it.
def connect(host, **options):
timeout = options.get("timeout", 30)
return host, timeout
print(connect("db.local", timout=5)) # ('db.local', 30)The caller wanted a 5-second timeout and got 30, with no error. If you know the option names, declare them as keyword-only parameters. Python then rejects unknown names for you.
def connect_strict(host, *, timeout=30):
return host, timeout
try:
connect_strict("db.local", timout=5)
except TypeError as error:
print(error) # connect_strict() got an unexpected keyword argument 'timout'Use **kwargs when you really forward options to something else, as in a wrapper. Otherwise name the parameters.
What `args` and `kwargs` actually are
Inside the function, args is a tuple and kwargs is a new dictionary. Three consequences follow.
args.append(4)raisesAttributeErrorbecause tuples are immutable. Uselist(args)if you need to change it.- Changing
kwargsdoes not change the caller's dictionary, because**copies the keys and values into the new one. - The copy is shallow. A list stored as a value is the same list object on both sides, so mutating it affects the caller.
def bump(*args, **kwargs):
kwargs["count"] = 99
return type(args).__name__
settings = {"count": 1}
print(bump(**settings)) # tuple
print(settings) # {'count': 1}Wrong parameter order
Python checks parameter order when it compiles the def, so a mistake is a SyntaxError before any code runs. Common mistakes are putting **kwargs before *args, and putting a parameter without a default after one that has a default (outside keyword-only position).
bad_signatures = [
"def f(**kwargs, *args): pass",
"def f(a=1, b): pass",
"def f(*args, *more): pass",
]
for source in bad_signatures:
try:
compile(source, "<example>", "exec")
except SyntaxError:
print("SyntaxError:", source)The valid order is: regular parameters, defaulted parameters, *args, keyword-only parameters, then **kwargs. Once *args or a bare * appears, later parameters may have or lack defaults in any order.
A debugging routine
When a call with * or ** fails, work through these checks in order.
Printing args and kwargs at the top of the function is the fastest check. A tuple with one nested list, or a dictionary with an odd key, shows the mistake right away.
Exercise
This call fails: def area(width, height): return width * height, then dims = {"width": 2, "height": 5} and area(3, **dims). What error is raised, and give two ways to fix it?
Show answer
It raises TypeError: area() got multiple values for argument 'width', because 3 fills width positionally and dims supplies it again. Fix it by calling area(**dims) (drop the positional value), or by removing "width" from the dictionary and calling area(3, height=5).
Exercise
A caller writes connect("db.local", timout=5) against a function defined as def connect(host, **options) and gets the default timeout with no error. Why, and how would you make the typo fail loudly?
Show answer
**options accepts any keyword name, so timout is stored in the dictionary and never read. Declare the option as a keyword-only parameter, def connect(host, *, timeout=30), so Python raises TypeError: unexpected keyword argument 'timout'.