NotImplementedError
NotImplementedError
is a built-in exception that signals a method or function hasn’t been implemented yet.
Typically, you’ll raise NotImplementedError
in a abstract base class (ABC) or interface to ensure that subclasses provide their own implementations. This exception also helps remind developers of any code that still needs completion.
NotImplementedError
Occurs When
A NotImplementedError
occurs when you call a method that explicitly raises this exception to indicate its implementation doesn’t exist yet.
NotImplementedError
Can Be Used When
- Indicating that a method in a base class needs to be implemented in a subclass
- Serving as a placeholder for future code development
- Alerting developers to incomplete code sections during development
NotImplementedError
Example
An example of when the exception appears:
>>> class Animal:
... def speak(self):
... raise NotImplementedError(
... "Subclasses must implement this method"
... )
...
>>> class Dog(Animal):
... pass
...
>>> dog = Dog()
>>> dog.speak()
Traceback (most recent call last):
...
NotImplementedError: Subclasses must implement this method
NotImplementedError
How to Fix It
To fix code that raises NotImplementedError
, you’ll need to implement the missing method in the subclass:
>>> class Animal:
... def speak(self):
... raise NotImplementedError(
... "Subclasses must implement this method"
... )
...
>>> class Dog(Animal):
... def speak(self):
... print("Woof!")
...
>>> dog = Dog()
>>> dog.speak()
Woof!
Related Resources
Tutorial
Implementing an Interface in Python
In this tutorial, you'll explore how to use a Python interface. You'll come to understand why interfaces are so useful and learn how to implement formal and informal interfaces in Python. You'll also examine the differences between Python interfaces and those in other programming languages.
For additional information on related topics, take a look at the following resources:
- Python's Built-in Exceptions: A Walkthrough With Examples (Tutorial)
- Python Exceptions: An Introduction (Tutorial)
- Object-Oriented Programming (OOP) in Python (Tutorial)
- Python Classes: The Power of Object-Oriented Programming (Tutorial)
- Python Interfaces: Object-Oriented Design Principles (Course)
- Implementing an Interface in Python (Quiz)
- Python's Built-in Exceptions: A Walkthrough With Examples (Quiz)
- Introduction to Python Exceptions (Course)
- Raising and Handling Python Exceptions (Course)
- Python Exceptions: An Introduction (Quiz)
- Intro to Object-Oriented Programming (OOP) in Python (Course)
- Object-Oriented Programming (OOP) in Python (Quiz)
- Class Concepts: Object-Oriented Programming in Python (Course)
- Inheritance and Internals: Object-Oriented Programming in Python (Course)
- Python Classes - The Power of Object-Oriented Programming (Quiz)