Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Body of abstract method in Python 3.5 [duplicate]

I have an abstract class, Model, with a few abstract methods, what should I put in the body of the methods?

  1. A return

    class Model(metaclass=ABCMeta):
        @abstractmethod
        def foo(self):
            return
    
  2. A pass

    class Model(metaclass=ABCMeta):
        @abstractmethod
        def foo(self):
            pass
    
  3. Raising a descriptive error

    class Model(metaclass=ABCMeta):
        @abstractmethod
        def foo(self):
            raise NotImplementedError("Class {class_name} doesn't implement {func_name} function"
                                  .format(class_name=self.__class__.__name__, func_name=self.foo.__name__))
    

Typically I would implement method 3 and raise an error, however it looks like it would be redundant, as Python raises an error for me:

>>> bar = module.Model()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Model with abstract methods foo

Between the options presented, which is best practice? Or is there another way I should handle this?

like image 961
shayaan Avatar asked Aug 22 '17 20:08

shayaan


People also ask

Can abstract method have body in Python?

In next Program, we create Myclass as an abstract super class with an abstract method calculate(). This method does not have any body within it. The way to create an abstract class is to derive it from a meta class ABC that belongs to abc (abstract base class) module as: class Abstractclass(ABC):

What does @abstractmethod do Python?

Last modified: 01 Feb 2022. Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes cannot be instantiated, and require subclasses to provide implementations for the abstract methods.

Can we override abstract method in Python?

A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods and properties are overridden. The abstract methods can be called using any of the normal 'super' call mechanisms. abstractmethod() may be used to declare abstract methods for properties and descriptors.

Should abstract method raise NotImplementedError?

If you run into the NotImplementedError, the recommended way to handle it is to implement the abstract method for which the error is being raised. Because the NotImplementedError is user-defined, Python can't raise this error on its own. So, you'll need to raise it by a package you're using or code your team wrote.


1 Answers

The best thing to put in the body of an abstractmethod (or abstractproperty) would be a docstring.

Then you don't need pass or return or ... because a return None is implicitly included - and a docstring makes this construct "compile" without a SyntaxError:

from abc import abstractmethod, ABCMeta

class Model(metaclass=ABCMeta):
    @abstractmethod
    def foo(self):
        """This method should implement how to foo the model."""

The docstring should then explain what should be implemented here so that subclassers know what is/was intended.

like image 71
MSeifert Avatar answered Oct 06 '22 23:10

MSeifert