When should you use raise NotImplementedError
in Python?
Is it primarily to remind yourself or your team to implement the methods in a class properly? I’m struggling to fully understand the use of an abstract class with this pattern:
class RectangularRoom(object):
def __init__(self, width, height):
raise NotImplementedError
def cleanTileAtPosition(self, pos):
raise NotImplementedError
def isTileCleaned(self, m, n):
raise NotImplementedError
Could you clarify how python NotImplementedError
fits in this context?
Hey @sndhu.rani
Here is the question to your answer:-
Using python notimplementederror
for Abstract Methods in Non-Abstract Classes
Raising NotImplementedError
is a common way to indicate that methods are meant to be overridden in subclasses. While Python doesn’t enforce abstract methods in regular classes, this approach acts as a clear signal for developers.
For example, in the RectangularRoom
class:
class RectangularRoom:
def cleanTileAtPosition(self, pos):
raise NotImplementedError("Subclasses must implement this method.")
Here, python notimplementederror
ensures that if a subclass does not implement the cleanTileAtPosition
method, an exception is raised, preventing incorrect usage of the class.
Hello Everyone,
Improving Abstract Method Definition with ABCs Instead of python notimplementederror
While manually using python notimplementederror
works, Python offers a cleaner and more enforceable solution through Abstract Base Classes (ABCs) in the abc
module.
Refactoring the previous example with ABC
and @abstractmethod
:
from abc import ABC, abstractmethod
class RectangularRoom(ABC):
@abstractmethod
def cleanTileAtPosition(self, pos):
pass
@abstractmethod
def isTileCleaned(self, m, n):
pass
This approach ensures that any attempt to instantiate RectangularRoom
or its subclasses without implementing the abstract methods raises an error at runtime, offering stricter control compared to python notimplementederror
.
Let me know if you have further doubts.
Hey All!
Using python notimplementederror as a Development Placeholder
In addition to indicating abstract methods, python notimplementederror
is useful during the development phase when a method’s logic isn’t ready yet. It acts as a placeholder to ensure the method isn’t unintentionally used.
For example:
class RectangularRoom:
def cleanTileAtPosition(self, pos):
# TODO: Implement this method later
raise NotImplementedError("cleanTileAtPosition is not yet implemented.")
def isTileCleaned(self, m, n):
# TODO: Add logic here
raise NotImplementedError("isTileCleaned is not yet implemented.")
Using python notimplementederror
here ensures that partially implemented methods don’t make it to production while signaling to other developers (or yourself) that these need further work. It’s a handy reminder in agile workflows.