Open In App

How To Avoid Notimplementederror In Python?

Last Updated : 22 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Python’s object-oriented architecture and versatility let programmers create dependable and scalable applications. Nevertheless, developers frequently encounter the NotImplementedError, especially when working with inheritance and abstract classes. This article will define NotImplementedError, explain its causes, and provide guidance on how to avoid it in your Python scripts.

What is Notimplementederror In Python?

When an abstract method that is supposed to be implemented by a subclass is not implemented, Python produces the NotImplementedError exception. This exception indicates that the method in question needs to be implemented in the subclass because it is not defined.

Why does NotImplementedError in Python Occur?

Below are some of the reason due to which NotImplementedError occurs in Python:

Abstract Methods Not Implemented

An abstract method declared in an abstract base class requires concrete implementation in its subclasses. If the subclass fails to implement the abstract method, a NotImplementedError is raised.

Python3




from abc import ABC, abstractmethod
 
class Shape(ABC):
    @abstractmethod
    def area(self):
        pass
 
class Square(Shape):
    def area(self):
        raise NotImplementedError("area() method not implemented for Square")
 
# Attempting to instantiate Square and call area()
try:
    square = Square()
    square.area()  # This will raise a NotImplementedError
except NotImplementedError as e:
    print("NotImplementedError:", e)


Output

NotImplementedError: area() method not implemented for Square

Incomplete Class Inheritance

Sometimes, the class hierarchy might not be fully implemented, leading to methods being left abstract without concrete implementation in any subclass. This situation can also trigger a NotImplementedError.

Python3




from abc import ABC, abstractmethod
 
class Animal(ABC):
    @abstractmethod
    def speak(self):
        pass
 
class Dog(Animal):
    def speak(self):
        raise NotImplementedError("speak() method not implemented for Dog")
 
# Attempting to instantiate Dog and call speak()
try:
    dog = Dog()
    dog.speak()
except NotImplementedError as e:
    print("NotImplementedError:", e)


Output

NotImplementedError: speak() method not implemented for Dog

Avoiding NotImplementedError in Python

Below are some of the solutions for NotImplementedError in Python:

Implement the Abstract Method

In this example, a Python abstract base class ‘Shape’ is defined with an abstract method ‘area’. A concrete class ‘Square’ is then created, inheriting from ‘Shape’ and implementing the ‘area’ method to calculate and return the area of a square based on its side length. An instance of ‘Square’ is instantiated with a side length of 5, and its area is printed to the console.

Python3




from abc import ABC, abstractmethod
 
class Shape(ABC):
    @abstractmethod
    def area(self):
        pass
 
class Square(Shape):
    def __init__(self, side):
        self.side = side
     
    def area(self):
        return self.side * self.side
 
square = Square(5)
print("Area of Square:", square.area())


Output

Area of Square: 25

Complete the Class Inheritance

In this example, a Python abstract base class ‘Animal’ is defined with an abstract method ‘speak’. A concrete class ‘Dog’ is then created, inheriting from ‘Animal’ and implementing the ‘speak’ method to return the specific sound a dog makes, in this case, “Woof!”. An instance of ‘Dog’ is instantiated, and its ‘speak’ method is called, printing “Woof!” to the console.

Python3




from abc import ABC, abstractmethod
 
class Animal(ABC):
    @abstractmethod
    def speak(self):
        pass
 
class Dog(Animal):
    def speak(self):
        return "Woof!"
 
dog = Dog()
print(dog.speak())  # Output: "Woof!"


Output

Woof!

Testing and Documentation

Clearly describe abstract methods in your documentation, outlining their goal and expected conduct. Write unit tests as well to ensure that abstract functions are appropriately overridden in subclasses and prevent NotImplementedError from occurring. Through adherence to these guidelines, Python developers can effectively prevent NotImplementedError in their programmes, guaranteeing codebase robustness and clarity.

Python3




from abc import ABC, abstractmethod
 
class Shape(ABC):
    @abstractmethod
    def area(self):
        pass
 
class Square(Shape):
    def __init__(self, side):
        self.side = side
     
    def area(self):
        return self.side * self.side
 
class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius
     
    def area(self):
        return 3.14 * self.radius * self.radius
 
# Testing
square = Square(5)
print("Area of Square:", square.area())
 
circle = Circle(3)
print("Area of Circle:", circle.area())


Output

Area of Square: 25
Area of Circle: 28.259999999999998

Conclusion

In conclusion, NotImplementedError is a typical issue that arises in Python while interacting with inheritance and abstract classes. However, by utilising abstract base classes, adding abstract methods in subclasses, and performing regular tests and documentation, developers can prevent this issue and build dependable and maintainable Python applications.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads