Python missing 1 required positional argument
TypeError: add() missing 1 required positional argument: 'b'
This error appears when you call a function with fewer values than it needs. The error message tells you everything: the function name comes first, the number after missing is how many values are missing, and the name in quotes at the end is the parameter that got no value. Compare the line that defines the function (def) with the number of values in the parentheses where you call it.
Cause 1. You passed too few values
def add(a, b) is a function that expects two values. If you pass only one, there is nothing to put in b.
Wrong code
def add(a, b): return a + b print(add(3))Traceback (most recent call last): File "main.py", line 4, in <module> TypeError: add() missing 1 required positional argument: 'b'
Fixed code
Pass as many values as there are parameters on the def line. If you want a value to be optional, give it a default value on the def line, like b=0.
If two or more are missing, all the names are listed, as in missing 2 required positional arguments: 'a' and 'b'. If you pass too many instead, you get takes 2 positional arguments but 3 were given.
Cause 2. You passed a whole list
Even if the list holds two values, the function received one value (one list). The list goes into the first parameter and the second one stays empty.
Wrong code
def area(w, h): return w * h size = [3, 4]print(area(size))Traceback (most recent call last): File "main.py", line 5, in <module> TypeError: area() missing 1 required positional argument: 'h'
Fixed code
Take the items out by index and pass them one by one, or put * in front of the list to unpack it.
def area(w, h): return w * h size = [3, 4]print(area(size[0], size[1]))print(area(*size))12 12
Cause 3. The message says 'self' is missing
If you call a class's method directly on the class name without creating an object, the missing name is 'self'. An object is supposed to go into self, but there is no object.
Wrong code
class Dog: def bark(self): print("woof") Dog.bark()Traceback (most recent call last): File "main.py", line 5, in <module> TypeError: Dog.bark() missing 1 required positional argument: 'self'
Fixed code
Create an object first by adding parentheses, as in Dog(), then call the method on that object. You never pass self yourself.
What to check when you see this error
- Read the function name in the error message, and the parameter name in quotes at the end.
- Find that function's
defline and count its parameters. Compare that with the number of values in the parentheses where you call it. - Check that a comma between values is not missing or replaced by another symbol.
- If the missing name is
'self', check that you created an object by putting()after the class name.