Sub topic 12
Reading TypeErrors from bad calls
This chapter assumes you can define and call functions, know the difference between parameters and arguments, and have met defaults, keyword-only (*) and positional-only (/) parameters, *args, **kwargs, and argument unpacking. Here you use that knowledge to read the TypeError messages Python raises when a call's arguments cannot be bound to a function's parameters.
The message wording below matches Python 3.10 and later, which put the qualified function name at the start. Older versions word some messages slightly differently, but the structure is the same.
Binding happens before the body runs
When you call a function, Python first matches arguments to parameters. The matching follows fixed steps:
- Positional arguments fill parameters from left to right.
- Keyword arguments fill parameters by name.
- Unfilled parameters take their defaults.
- Any parameter still empty is an error, and so is any argument with nowhere to go.
If binding fails, Python raises TypeError before the first line of the function body runs. Two consequences follow. A binding error is always a problem at the call site or in the signature, never in the body. The traceback's last frame points at the call line, and no frame inside the function appears.
A harness for provoking errors
The following script defines a helper that calls a function and prints the TypeError message. Its first parameter is positional-only, so a keyword argument named func can never collide with it.
def show(func, /, *args, **kwargs):
try:
func(*args, **kwargs)
except TypeError as exc:
print(f"TypeError: {exc}")
def greet(name, greeting="Hello", punctuation="!"):
return f"{greeting}, {name}{punctuation}"
def area(w, h):
return w * h
show(greet)
show(area)
show(area, 1, 2, 3)
show(greet, "Ada", "Hi", "?", "extra")
show(greet, "Ada", name="Bob")
show(greet, "Ada", greting="Hi")Running it prints:
TypeError: greet() missing 1 required positional argument: 'name'
TypeError: area() missing 2 required positional arguments: 'w' and 'h'
TypeError: area() takes 2 positional arguments but 3 were given
TypeError: greet() takes from 1 to 3 positional arguments but 4 were given
TypeError: greet() got multiple values for argument 'name'
TypeError: greet() got an unexpected keyword argument 'greting'Each message names the function, states the rule that failed, and usually names the parameter involved. The sections below take them in turn.
Missing arguments
missing N required positional argument(s) means a parameter with no default received nothing. The message lists the names, so you can see exactly which ones. Fix it by passing the value, or by giving the parameter a default if a default makes sense.
Keyword-only parameters have their own wording. A keyword-only parameter without a default is required, and omitting it produces a different message:
def show(func, /, *args, **kwargs):
try:
func(*args, **kwargs)
except TypeError as exc:
print(f"TypeError: {exc}")
def fetch(url, *, retries):
return url, retries
show(fetch, "http://example.com")
show(fetch, "http://example.com", 3)TypeError: fetch() missing 1 required keyword-only argument: 'retries'
TypeError: fetch() takes 1 positional argument but 2 were givenThe second message is the common mistake. The caller assumed retries could be passed by position. The signature says the argument count is 1, because * ends the positional parameters. The fix is to call fetch(url, retries=3).
Too many positional arguments
The message takes N positional arguments but M were given reports two numbers, and the wording of the first depends on whether defaults exist.
- With no defaults, it says
takes 2 positional arguments, one exact number. - With defaults, it says
takes from 1 to 3 positional arguments, a range from the required count to the total.
Keyword-only parameters are not counted in either number. This explains a message that looks wrong at first glance:
def show(func, /, *args, **kwargs):
try:
func(*args, **kwargs)
except TypeError as exc:
print(f"TypeError: {exc}")
def connect(host, port=5432, *, timeout=10, ssl=True):
return (host, port, timeout, ssl)
show(connect, "db.local", 5432, 5)TypeError: connect() takes from 1 to 2 positional arguments but 3 were givenThe signature has four parameters, yet the message says 2. The two after * can only be passed by name, so the third positional value has no parameter to fill. When the count in the message is smaller than the number of parameters you see in the signature, look for a * marker.
The hidden self
For a method called on an instance, Python passes the instance as the first argument. The count in the message includes it:
def show(func, /, *args, **kwargs):
try:
func(*args, **kwargs)
except TypeError as exc:
print(f"TypeError: {exc}")
class Server:
def start(self, port):
return port
def stop():
return None
show(Server().start, 8080, 9090)
show(Server().stop)TypeError: Server.start() takes 2 positional arguments but 3 were given
TypeError: Server.stop() takes 0 positional arguments but 1 was givenIn the first call you passed two arguments, but the message says 3 were given, because self counts. In the second call you passed none, yet 1 was given. This second pattern, where the message says one more argument was given than you wrote, almost always means the method definition forgot self.
Multiple values for one parameter
got multiple values for argument 'name' means the same parameter was filled twice. The usual cause is a positional argument that already landed on the parameter, followed by a keyword argument naming it:
def greet(name, greeting="Hello"):
return f"{greeting}, {name}"
try:
greet("Hi", name="Ada")
except TypeError as exc:
print(f"TypeError: {exc}")TypeError: greet() got multiple values for argument 'name'The first positional value "Hi" filled name, so the keyword name="Ada" collides with it. This often happens when someone inserts a new parameter in the middle of a signature. Existing positional callers shift by one place, and callers who also passed that name by keyword now collide.
A related error appears with double-star unpacking. If two mappings supply the same key, the call fails before binding even starts, with got multiple values for keyword argument 'a'.
Unexpected keyword arguments
got an unexpected keyword argument 'greting' almost always means a typo or a renamed parameter. Compare the name in the message against the signature character by character. Some newer Python versions append a "Did you mean" hint to the printed traceback, but you cannot rely on that.
Unpacking can produce this error far from where the mistake was made. A dict built elsewhere may carry a key the function does not accept:
def connect(host, port=5432, *, timeout=10):
return (host, port, timeout)
options = {"timeout": 5, "retries": 3}
try:
connect("db.local", **options)
except TypeError as exc:
print(f"TypeError: {exc}")TypeError: connect() got an unexpected keyword argument 'retries'The call line looks fine, so inspect the dict's contents. If the function should tolerate extra options, it needs a **kwargs parameter. If it should not, filter the dict before unpacking.
Positional-only parameters passed by keyword
A positional-only parameter cannot be bound by name. Without a **kwargs parameter, Python says so directly:
def clamp(value, /, low=0, high=100):
return max(low, min(value, high))
try:
clamp(value=5)
except TypeError as exc:
print(f"TypeError: {exc}")TypeError: clamp() got some positional-only arguments passed as keyword arguments: 'value'If the function does have **kwargs, the same call raises no error and takes a different path. The name goes into the kwargs dict instead:
def f(a, /, **kw):
return a, kw
print(f(1, a=2))(1, {'a': 2})Here a the positional parameter and 'a' the keyword key are different things. This is a deliberate feature, and it lets a function accept arbitrary keys without clashing with its own parameter names.
Mistakes that are not TypeErrors
Some bad calls fail earlier or differently:
- A positional argument after a keyword argument, as in
greet(name="Ada", "Hi"), is aSyntaxError: positional argument follows keyword argument. Python rejects it when compiling the file, before any code runs. - Unpacking something that is not iterable, as in
f(*5), raises aTypeErrorsaying the argument after*must be an iterable. - Unpacking a non-mapping with
**raises aTypeErrorsaying the argument after**must be a mapping. - Passing a dict with non-string keys, as in
f(**{1: 2}), raises aTypeErrorsaying keywords must be strings.
A reading checklist
| Message fragment | Likely cause | First thing to check |
|---|---|---|
| `missing N required positional argument` | Parameter without default got nothing | Names listed in the message |
| `missing 1 required keyword-only argument` | Name after `*` was not passed | Add `name=value` to the call |
| `takes N positional arguments but M were given` | Extra positional value | A `*` marker, or `self` in the count |
| `takes from A to B positional arguments` | Same, with defaults present | Required count A and total B |
| `got multiple values for argument` | Positional and keyword fill the same parameter | Parameter order after a signature change |
| `got an unexpected keyword argument` | Typo, renamed parameter, or stray dict key | Spelling, and the contents of unpacked dicts |
| `positional-only arguments passed as keyword` | Name used for a parameter before `/` | Pass it by position |
When a message surprises you, run inspect.signature(func) on the function. It shows the real parameter list, including the * and / markers, and often explains the numbers in the message immediately.
Exercise
A caller runs request("http://x", 30) against def request(url, *, timeout=10). What exact kind of message does Python raise, what does its count say, and what is the fix?
Show answer
It raises TypeError: request() takes 1 positional argument but 2 were given. The count is 1 because timeout follows * and is keyword-only, so the second positional value has no parameter to fill. The fix is to call request("http://x", timeout=30).
Exercise
Given class Cache: def get(key): return key, calling Cache().get("a") raises Cache.get() takes 0 positional arguments but 1 was given. Why does it say 1 when you passed one argument, and what is the fix?
Show answer
The instance is passed automatically as the first argument, so Python received the instance plus nothing else, then counted "a" as the second. The message counts the instance as the argument given and shows that the signature has no slot for it. Adding self as the first parameter fixes it: def get(self, key).