This page explains Python NotImplemented
constant, its typical use cases, and its difference from NotImplementedError
.
Typical use cases
The built-in NotImplemented
constant is used to indicate that an operation or method is not implemented for a given object.
It is typically used with comparison methods such as __eq__()
, __lt__()
, __gt__()
, when comparison between the two objects does not make sense or is not implemented.
In abstract base classes, a method can be defined but left unimplemented by returning the NotImplemented
constant. This allows individual subclasses to provide their own implementation. If a subclass does not have an implementation, a TypeError
will be raised when the method is called.
NotImplementedType
The NotImplenented
constant has its own special data type NotImplementedType
.
>>> type(NotImplemented) <class 'NotImplementedType'>
NotImplemented vs. NotImplementedError
NotImplemented
(constant) is different from NotImplementedError
(exception).
>>> a = NotImplemented >>> a NotImplemented >>> type(a) <class 'NotImplementedType'> >>> >>> b = NotImplementedError >>> b <class 'NotImplementedError'> >>> type(b) <class 'type'>
While NotImplementedError
can be raised, NotImplemented
is a constant – not exception, so trying to raise it will raise a TypeError
.
>>> raise NotImplementedError Traceback (most recent call last): File "<stdin>", line 1, in <module> NotImplementedError >>> raise NotImplemented Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: exceptions must derive from BaseException
Official documentation
NotImplemented
(constant)
Official documentation at docs.python.org
NotImplementedError
(exception)
https://docs.python.org/3/library/exceptions.html#NotImplementedError