While studying the source code of the numbers.py
module from build-in lib, I came across two variants of @abstractmethod
(with and without the NotImplementedError
raise). Example:
class Complex(ABC):
@abstractmethod
def __complex__(self):
"""Return a builtin complex instance. Called for complex(self)."""
@abstractmethod
def __neg__(self):
"""-self"""
raise NotImplementedError
Next, I created a child class:
class MyComplex(Complex):
def __complex__(self):
return complex(1, 1)
def __neg__(self):
return complex(-1, -1)
After playing with this code for a bit, I found only one difference:
>>> c = MyComplex()
>>> Complex.__complex__(c)
>>> Complex.__neg__(c)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/maskalev/dev/foo/bar.py", line 15, in __neg__
raise NotImplementedError
NotImplementedError
when calling the __complex__()
method, None
is returned, and when calling __neg__()
, an exception is raised (which, in fact, is described in the code).
So I have some questions:
- Is this the only difference?
- Why is
NotImplementedError
raising not used in the first case, but used in the second? (Isn’t it better to do it uniformly?) - What is the best practice? (I think it’s better to raise an exception explicitly, but maybe I don’t see the whole picture.)
2