Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I put abstract classes in a python package?

I am adding abstract classes to my python package like this:

class AbstractClass(ABC):

    @abstractmethod
    def do_something(self):
        pass

There will be multiple subclasses that inherit from AbstractClass like this:

class SubClass(AbstractClass):

    def do_something(self):
        pass

I am wondering if there are any conventions for python packages regarding abstract classes that I am unaware of.

  • should the abstract classes be separated from the subclasses, or should they all be in the same directory?
  • what about naming of abstract functions, any conventions there?

I realize this is fairly subjective. I am asking for opinions, not what is 'right' or 'wrong'

Thanks!

like image 977
Garrett Johnson Avatar asked Sep 16 '20 18:09

Garrett Johnson


1 Answers

No convention comes to mind. If this is all for just one project, I'd be looking to put the abstract class in with the concrete subclasses at whatever level they're at. If all the subclasses were in one file, then I'd put the abstract class in that file too. If all the subclasses were in individual files in a dir, I'd put the abstract class right next to them in its own file. The reason I'd put the abstract class somewhere else is if I'm separating off utility code that can be reused with other projects. In short, an abstract class is just a piece of code. Just another class. Treat it like any other.

As far as naming, the natural naming of the class given what it is/does is usually enough. If your abstract class were Animal, and your subclasses were Goat, Horse, etc., I'd see no reason to call your abstract class AbstractAnimal, as it's pretty clear already what's going on...that you wouldn't instantiate Animal directly. Also, if you're looking at a class thinking of reusing it, and you see an abstract method in it, then you know it's abstract.

like image 157
CryptoFool Avatar answered Sep 19 '22 13:09

CryptoFool