Understanding Python's TypeError, Missing 1 required positional argument


Python error sometimes can be confusing, especially for beginners. A common source of confusion is the TypeError related to argument mismatch, often encountered when working with class methods. Let’s break down this error to help you understand and resolve it effectively.

The Scenario

Consider a simple class in Python:

class MyClass:
def my_method(self, name):
print(f"Name is {name}")

my_method is a method of MyClass that requires two arguments: self and name. self is a reference to the instance of the class (automatically passed when you call a method on an object), and name is an additional argument that needs to be provided.

The Common Mistake

A frequent mistake is attempting to call my_method directly on the class, without creating an instance:

MyClass.my_method("example name")

The Error

Doing this results in the following error:

TypeError: my_method() missing 1 required positional argument: 'name'

Why This Error?

This error message can be misleading because it seems like you provided the name argument. However, the root cause is different:

  • Instance Methods Need self: Instance methods are designed to operate on an instance of the class (an object). When you call an instance method, Python automatically passes the instance as the first argument, which is self.

  • Direct Class Method Call: When you call the method directly on the class (e.g., MyClass.my_method), Python doesn’t have an instance to pass as self. It then interprets the first argument you provide (“example name”) as self, not as name.

  • Argument Mismatch: As a result, Python thinks you haven’t provided the name argument, leading to the TypeError.

The Solution

To resolve this error, you need to call the method on an instance of the class:

instance = MyClass()
instance.my_method("example name")

In this corrected approach, instance.my_method("example name") passes instance as self and “example name” as name, aligning with the method’s parameters.


Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !
  TOC