Pure virtual methods in Python
Asked Answered
A

1

14

What is the ideologically correct way of implementing pure virtual methods in Python?

Just raising NotImplementedError in the methods?

Or is there a better way?

Thank you!

Amphiaster answered 6/2, 2014 at 18:17 Comment(0)
T
15

While it's not uncommon to see people using NotImplementedError, some will argue that the "proper" way to do it (since python 2.6) is using a Abstract Base Class, through the abc module:

from abc import ABCMeta, abstractmethod

class MyAbstractClass(object):
    __metaclass__=ABCMeta
    @abstractmethod
    def my_abstract_method():
        pass

There's two main (potential) advantages in using abc over using NotImplementedError.

Firstly, You won't be able to instantiate the abstract class (without needing __init__ hacks):

>>> MyAbstractClass()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class MyAbstractClass with abstract methods my_abstract_method

Secondly, you won't be able to instantiate any subclass that doesn't implement all abstract methods:

>>> class MyConcreteClass(MyAbstractClass):
...     pass
... 
>>> MyConcreteClass()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class MyConcreteClass with abstract methods my_abstract_method

Here's a more complete overview on abstract base classes

Twila answered 6/2, 2014 at 18:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.