Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should I put in the body of an abstract method?

Say I have the following abstract class Foo:

import abc

class Foo(abc.ABC):

    @abc.abstractmethod
    def bar(self):
        raise NotImplementedError

What should I put in the body of the bar method?

I see a lot of code that has raise NotImplementedError, as shown above. However, this seems redundant, since any subclass that does not implement bar will raise the TypeError: Can't instantiate abstract class Foo with abstract methods bar when it is instantiated.

Is it Pythonic to leave bar empty, as follows:

import abc

class Foo(abc.ABC):

    @abc.abstractmethod
    def bar(self):
        ...

This is what is done in the Python docs for Abstract Base Classes, but I'm not sure if that's just a placeholder or an actual example of how to write code.

If it's ok to leave bar with only three dots (...), when should I use NotImplementedError?

like image 539
ostrokach Avatar asked Nov 30 '16 17:11

ostrokach


People also ask

Can we have body in abstract method?

An abstract method is declared by abstract keyword, such methods cannot have a body.

Why abstract method does not specify a body?

You can not specify a body to abstract methods. Abstract methods means they are incomplete.

Can abstract methods in a abstract class have a body?

Abstract Classes and Methods Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class). Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from).


1 Answers

The documentation does aim to give you an example. You don't have to follow it.

You could provide a default; subclasses are still free to use super() to call your implementation. This is what most of the collections.abc classes do; see the source code.

Size for example, returns 0 for __len__:

class Sized(metaclass=ABCMeta):
    # ...
    @abstractmethod
    def __len__(self):
        return 0
like image 89
Martijn Pieters Avatar answered Sep 30 '22 15:09

Martijn Pieters