TypeError: takes 0 positional arguments but 2 were given

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

TypeError: takes 0 positional arguments but 2 were given #

The Python "TypeError: takes 0 positional arguments but 2 were given" occurs for multiple reasons:

  1. Forgetting to specify the arguments in a function.
  2. Passing 2 arguments to a function that doesn't take any arguments.
  3. Overriding a built-in function by mistake.
  4. Forgetting to specify the self arg in a class method.

typeerror takes 0 positional arguments but 2 were given

Here is an example of how the error occurs.

main.py
def do_math(): return a + b # ⛔️ TypeError: do_math() takes 0 positional arguments but 2 were given result = do_math(10, 15)

We forgot to specify the arguments the do_math function takes and called the function passing it 2 arguments which caused the error.

To solve the error, make sure to specify the arguments the function takes in its definition.

main.py
def do_math(a, b): return a + b result = do_math(10, 15) print(result) # 👉️ 25

Now the function takes 2 arguments - a and b and gets passed 2 arguments, so the error is resolved.

If your function doesn't need to take any arguments but gets called with 2, you have to remove the arguments from the function call.

main.py
def do_math(): return 10 + 10 result = do_math() print(result) # 👉️ 20

Now the function doesn't take any arguments and doesn't get passed any.

If you got the error when working with classes, make sure to specify self as the first argument in your class methods.

main.py
class Employee(): # 👇️ specify self as first arg def get_name(self, name): return name emp = Employee() print(emp.get_name('Alice')) # 👉️ "Alice"
Python automatically passes self to the class method when it is called.

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

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.

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.

Use the search field on my Home Page to filter through my more than 1,000 articles.