Sub topic 9
Common Pitfalls and Errors
This chapter covers the mistakes people most often make with *args, **kwargs and the matching call-site unpacking. For each one you will see the code that fails, the error Python reports, and the fix.
It assumes you can already define functions with *args and **kwargs, know the required parameter order, and have used * and ** in calls. You should also be comfortable with tuples, dictionaries and dict.items().
Reading the error messages
Most argument mistakes raise TypeError, and the message names the function and the parameter involved. A few mistakes are caught earlier, as a SyntaxError, because the signature or call is malformed before any code runs.
| Message (wording varies slightly between Python versions) | Usual cause |
|---|---|
| `got multiple values for argument 'x'` | A value arrived both positionally and by keyword |
| `got multiple values for keyword argument 'x'` | Two `**` dictionaries, or a `**` dictionary plus an explicit `x=`, supply the same key |
| `got an unexpected keyword argument 'x'` | The function has no parameter `x` and no `**kwargs` |
| `missing 1 required positional argument: 'x'` | A required value was never supplied, often because a list was not unpacked |
| `missing 1 required keyword-only argument: 'x'` | A parameter after `*` has no default and was not passed by name |
| `argument after * must be an iterable` | A single `*` was applied to something like an `int` |
| `argument after ** must be a mapping` | A double `**` was applied to something that is not a dictionary-like object |
Supplying the same parameter twice
The chapter's central error is that every parameter can receive only one value. Positional values are matched to parameters first, then keyword values. If a keyword names a parameter that a positional value already filled, Python refuses the call.
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 conflict happens when you unpack two dictionaries that share a key. Unlike a dictionary literal, where the later key silently wins, a call refuses duplicate keys.
def area(width, height):
return width * height
base = {"width": 2, "height": 3}
override = {"height": 10}
try:
area(**base, **override)
except TypeError as error:
print(error) # area() got multiple values for keyword argument 'height'
# Merge first, so the later dictionary wins, then unpack once.
print(area(**{**base, **override})) # 20If you want "later wins" behavior, merge into one dictionary with {**a, **b} and unpack the result. If a duplicate means a bug in your data, the TypeError is useful, so let it surface.
Name collisions in wrappers
A generic helper that has its own named parameter can collide with a caller's keyword. Here call takes a parameter named func, so a caller cannot forward a keyword that is also named func.
def call(func, *args, **kwargs):
return func(*args, **kwargs)
try:
call(dict, func=1)
except TypeError as error:
print(error) # call() got multiple values for argument 'func'
def safe_call(func, /, *args, **kwargs):
return func(*args, **kwargs)
print(safe_call(dict, func=1)) # {'func': 1}Making func positional-only with / removes the name from the keyword namespace, so func=1 flows into **kwargs. Use this whenever a function forwards arbitrary keywords it does not control.
Forgetting the star at the call site
Passing a collection without * hands the function one argument, the collection itself. The resulting error often points at a missing argument, not at the star.
def area(width, height):
return width * height
size = (3, 4)
try:
area(size)
except TypeError as error:
print(error) # area() missing 1 required positional argument: 'height'
print(area(*size)) # 12The reverse also occurs. A function that declares *args receives a single list as a one-element tuple when you forget the star.
def show(*args):
print(args)
show([1, 2]) # ([1, 2],)
show(*[1, 2]) # (1, 2)Unpacking the wrong kind of object
A single * accepts any iterable, and that is broader than most people expect. Strings unpack into characters. Dictionaries unpack into their keys.
def show(*args):
print(args)
show("abc") # ('abc',)
show(*"abc") # ('a', 'b', 'c')
show(*{"width": 2, "height": 5}) # ('width', 'height')Applying * to a dictionary rarely does what you want. Use ** to pass the key-value pairs as keywords, or *d.values() if you really want only the values.
Two other mistakes are caught with a clear TypeError. show(*5) fails because an int is not iterable. show(**[1, 2]) fails because a list is not a mapping. Check that the object after * is a sequence or other iterable, and that the object after ** is a dictionary or another mapping.
Dictionary keys must be strings
Every key in a ** dictionary becomes a keyword name, so every key must be a str.
def show(**kwargs):
return kwargs
try:
show(**{1: "one"})
except TypeError as error:
print(type(error).__name__) # TypeError
# Strings that are not valid identifiers are accepted by **kwargs:
print(show(**{"my-key": 1, "two words": 2}))
# {'my-key': 1, 'two words': 2}The second case is legal but unusual. A function with named parameters cannot receive "my-key", but a function with **kwargs can collect it. Be careful when you later forward such a dictionary to a function that names its parameters.
Iterators are used up
Unpacking an iterator consumes it completely before the call starts. Reusing the same iterator gives you nothing the second time. An infinite generator never finishes unpacking and exhausts your memory.
def total(*args):
return sum(args)
numbers = iter([1, 2, 3])
print(total(*numbers)) # 6
print(total(*numbers)) # 0, the iterator is already exhaustedIf you need to reuse the values, keep them in a list or tuple instead of an iterator.
Treating `args` and `kwargs` like the caller's objects
Inside the function, args is always a tuple and kwargs is always a dict. Two consequences catch people out.
First, a tuple has no append, sort or item assignment. Convert it when you need to change the contents.
def collect(*args):
try:
args.append(1)
except AttributeError as error:
print(error) # 'tuple' object has no attribute 'append'
items = list(args)
items.append(1)
return items
print(collect(5, 6)) # [5, 6, 1]Second, kwargs is a new dictionary built for each call. Adding or changing a key does not touch the dictionary you unpacked at the call site.
def tweak(**kwargs):
kwargs["x"] = 99
return kwargs
original = {"x": 1}
result = tweak(**original)
print(original) # {'x': 1}
print(result) # {'x': 99}The copy is shallow. The values are the same objects, so mutating a list or dictionary stored as a value changes the caller's data.
def append_item(**kwargs):
kwargs["items"].append("new")
data = {"items": []}
append_item(**data)
print(data) # {'items': ['new']}Typos that `**kwargs` hides
A function with only named parameters rejects a misspelled keyword immediately. A function with **kwargs accepts it and moves on, so the setting is ignored without any error.
def connect(host, **options):
timeout = options.get("timeout", 10)
return host, timeout
print(connect("db", timout=1)) # ('db', 10), the typo is silently ignoredThere are two good fixes. The first is to name the options you support as keyword-only parameters, which restores the error. The second is to remove each known option with pop and reject whatever is left.
def connect(host, **options):
timeout = options.pop("timeout", 10)
retries = options.pop("retries", 3)
if options:
raise TypeError(f"connect() got unexpected options: {sorted(options)}")
return host, timeout, retries
print(connect("db", timeout=1)) # ('db', 1, 3)
try:
connect("db", timout=1)
except TypeError as error:
print(error) # connect() got unexpected options: ['timout']Prefer explicit parameters whenever you know the names. Keep **kwargs for code that truly forwards options to something else.
Mistakes in wrappers and decorators
Forwarding wrappers have four typical bugs, and each fails in a different way.
- Dropping `kwargs
.** A wrapper declared asdef wrapper(*args)` breaks as soon as someone calls the wrapped function with a keyword. - Forgetting
return. The wrapper calls the function but discards the result, so every call returnsNone. - Omitting
functools.wraps. The decorated function reports the namewrapperand loses its docstring, which confuses debuggers, logs and documentation tools. - Changing arguments by accident. Reordering, filtering or renaming values inside the wrapper changes behavior in ways the caller cannot see.
import functools
def no_return(func):
def wrapper(*args, **kwargs):
func(*args, **kwargs) # result is discarded
return wrapper
def with_wraps(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def args_only(func):
def wrapper(*args):
return func(*args)
return wrapper
@no_return
def one():
"""Return 1."""
return 1
@with_wraps
def two():
"""Return 2."""
return 2
@args_only
def add(a, b=0):
return a + b
print(one(), one.__name__, one.__doc__) # None wrapper None
print(two(), two.__name__, two.__doc__) # 2 two Return 2.
try:
add(1, b=2)
except TypeError as error:
print(error) # wrapper() got an unexpected keyword argument 'b'Note that the error in the last case names wrapper, not add. When a traceback points at a function you never wrote, look for a decorator that forwards too little.
Malformed signatures and calls
Some argument mistakes never reach runtime. Python rejects them while compiling the code. The snippet below uses compile so you can see each failure without stopping your script.
bad_sources = [
"def f(**kwargs, *args): pass", # *args must come before **kwargs
"def f(a=1, b): pass", # non-default parameter after a default
"def f(*args, *more): pass", # only one *args allowed
"def f(**kwargs, **more): pass", # only one **kwargs allowed
"f(a=1, 2)", # positional argument after a keyword
]
for source in bad_sources:
try:
compile(source, "<demo>", "exec")
except SyntaxError:
print(f"SyntaxError: {source}")All five lines print. In a definition the order is regular parameters, defaults, *args, keyword-only parameters, then **kwargs. In a call, positional values come before keyword values. **kwargs is always last in both.
Using `*args` and `**kwargs` too eagerly
A signature of (*args, **kwargs) accepts anything, and that is the problem. Callers lose the parameter names, so editors cannot suggest them, help() shows nothing useful, and a wrong call fails deep inside the function it was forwarded to.
Use explicit parameters when the set of inputs is known and small. Use *args and **kwargs when you really do forward to another callable, when you accept an unbounded number of similar values (like print), or when a subclass overrides a method and must pass unknown options up to its parent.
Exercises
Exercise
A function is defined as def area(width, height): return width * height. A colleague calls it as area(*{"width": 2, "height": 5}). What happens, and what is the one-character-level fix?
Show answer
A single * unpacks a dictionary into its keys, so the call becomes area("width", "height"). Python then tries to multiply two strings and raises a TypeError (you cannot multiply a sequence by a non-integer of type str). Use ** to pass key-value pairs as keyword arguments: area(**{"width": 2, "height": 5}) returns 10.
Exercise
A decorator defines def wrapper(*args): return func(*args). The decorated function is def add(a, b=0). Why does add(1, b=2) fail, and how do you fix the decorator?
Show answer
The wrapper has no **kwargs, so the keyword b=2 has nowhere to go and Python raises TypeError: wrapper() got an unexpected keyword argument 'b'. Change the wrapper to def wrapper(*args, **kwargs): return func(*args, **kwargs) and add @functools.wraps(func) so the name and docstring are preserved.
Exercise
What does f(**{"a": 1}, a=2) do for def f(a): return a, and how does it differ from {**{"a": 1}, "a": 2}?
Show answer
The call raises TypeError: f() got multiple values for keyword argument 'a', because a call refuses duplicate keyword names. The dictionary literal does not raise an error. The later key wins, so it produces {'a': 2}.