irahorecka
irahorecka

Reputation: 1807

Catching TypeError: Missing 1 required positional argument: 'self'

I wonder if it's possible to catch the TypeError thrown when a user calls an instance method without instantiation. Something to allow me to write an exception message like:

"Class instance is required for 'this_method'", instead of

"Missing 1 required positional argument: 'self'".

Upvotes: 0

Views: 2550

Answers (1)

Force Bolt
Force Bolt

Reputation: 1221

Here is a simple code snipped of Calc class with classmethod called addtwo that simply adds two numbers:

class Calc():
    a: int
    b: int
    
    def addtwo(self,a,b):
        self.a=a
        self.b=b
        return self.a+self.b
        
if __name__=='__main__':
        print(Calc.addtwo(a=2,b=4))

If you run this, you will get:

TypeError: addtwo() missing 1 required positional argument: 'self'

which is the exact error that you encountered. According to your requirements, it can be easily fixed by enclosing the code inside a try-except block like this:

class Calc():
    a: int
    b: int
    
    def addtwo(self,a,b):
        self.a=a
        self.b=b
        return self.a+self.b
        
if __name__=='__main__':
    try:
        print(Calc.addtwo(a=2,b=4))
    except TypeError:
        print("Class instance is required for this_method")

and on running this, you will get:

Class instance is required for this_method

However, the standard way of calling a class method should be like this:

if __name__=='__main__':
    instance = Calc()
    print(instance.addtwo(a=2,b=4))

Hope it helped.

Upvotes: 3

Related Questions