Python’s `NotImplemented` Type

This post discusses Python’s NotImplemented built-in constant/type; what it is, what it means and when it should be used.

What is it?

>>> type(NotImplemented)
<type 'NotImplementedType'>
>>> None = 'hello'
...
SyntaxError: can't assign to keyword
>>> NotImplemented
NotImplemented
>>> NotImplemented = 'do not'
>>> NotImplemented
'do not'

What does it mean and when should it be used?

NotImplemented is a special value which should be returned by the binary special methods (e.g. __eq__(), __lt__(), __add__(), __rsub__(), etc.) to indicate that the operation is not implemented with respect to the other type; it may be returned by the in-place binary special methods (e.g. __imul__(), __iand__()) for the same purpose. Also, its truth value is True:

>>> bool(NotImplemented)
True
# example.pyclass A(object):
def __init__(self, value):
self.value = value
def __eq__(self, other):
if isinstance(other, A):
print('Comparing an A with an A')
return other.value == self.value
if isinstance(other, B):
print('Comparing an A with a B')
return other.value == self.value
print('Could not compare A with the other class')
return NotImplemented
class B(object):
def __init__(self, value):
self.value = value
def __eq__(self, other):
if isinstance(other, B):
print('Comparing a B with another B')
return other.value == self.value
print('Could not compare B with the other class')
return NotImplemented
>>> from example import A, B
>>> a1 = A(1)
>>> b1 = B(1)
>>> a1 == a1
Comparing an A with an A
True
>>> b1 == b1
Comparing a B with another B
True
>>> a1 == b1
Comparing an A with a B
True
>>> b1 == a1
Could not compare B against the other class
Comparing an A with a B
True

Written by

Co-founder & CTO at Metaview. Previously, Palantir, Osper, and Morgan Stanley. I love a silly salmon with a good egg. @s16h_ on Twitter.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store