TypeError: takes 1 positional argument but 2 were given

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: takes 1 positional argument but 2 were given #

The Python "TypeError: takes 1 positional argument but 2 were given" occurs for multiple reasons:

  1. Forgetting to specify the self argument in a class method.
  2. Forgetting to specify a second argument in a function's definition.
  3. Passing two arguments to a function that only takes one.
  4. Overriding a built-in function by mistake.

typeerror takes 1 positional argument but 2 were given

Here is an example of how the error occurs.

main.py
class Employee(): # 👇️ forgot to specify `self` arg def get_name(name): return name emp = Employee() # ⛔️ TypeError: Employee.get_name() takes 1 positional argument but 2 were given print(emp.get_name('Alice'))

We forgot to specify the self argument in the definition of the get_name class method.

Python automatically passes self to the class method when it is called, so a method that takes 1 argument gets passed 2 arguments which causes the error.
main.py
class Employee(): # ✅ specify self as first arg def get_name(self, name): return name emp = Employee() print(emp.get_name('Alice')) # 👉️ "Alice"

self represents an instance of the class, so when we assign a variable as

Specifying the self argument in the method's definition solves the error.

If your method doesn't make use of the self argument, you can declare a static method.

main.py
class Employee(): @staticmethod def get_name(name): return name emp = Employee() print(emp.get_name('Alice')) # 👉️ "Alice"

A static method does not receive an implicit first argument and can be called on the class or on an instance of the class.

The error is also caused when you forget to specify the second argument in a function's definition or pass 2 arguments to a function that only takes 1.
main.py
# ⛔️ TypeError: do_math() takes 1 positional argument but 2 were given def do_math(a): return a * a result = do_math(5, 10)

The do_math function takes a single argument but it gets called with 2.

In this situation, we either have to update the function's declaration and take a second argument or remove the second argument from the function call.

Here is an example of removing the argument from the function call.

main.py
def do_math(a): return a * a result = do_math(5) print(result) # 👉️ 25

And here is an example of specifying the second argument in the function's definition.

main.py
def do_math(a, b): return a * b result = do_math(5, 10) print(result) # 👉️ 50

Make sure you aren't overriding any built-in functions or classes by declaring a function with the same name, as that can also cause the error.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.