Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it pythonic to use interfaces / abstract base classes?

I cannot find much advantage in them besides kind of documentation purpose. Python will warn me if I forget to implement a method I defined in a ABC but since I do not reference my objects by their interfaces I can forget to declare methods in their interfaces and I won't event notice it. Is it common practice to use ABC's for interface-like behaviour?

like image 644
tyrondis Avatar asked Mar 12 '11 17:03

tyrondis


People also ask

Which is better to use interface or abstract class?

The short answer: An abstract class allows you to create functionality that subclasses can implement or override. An interface only allows you to define functionality, not implement it. And whereas a class can extend only one abstract class, it can take advantage of multiple interfaces.

Are abstract classes Pythonic?

Python doesn't directly support abstract classes. But it does offer a module that allows you to define abstract classes. To define an abstract class, you use the abc (abstract base class) module. The abc module provides you with the infrastructure for defining abstract base classes.

Are interfaces Pythonic?

Unfortunately, Python doesn't have interfaces, or at least, not quite built into the language. Enter Python's abstract base class, or, cutely, ABC. Functionally, abstract base classes let you define a class with abstract methods, which all subclasses must implement in order to be initialized.

Why would one use an interface instead of an abstract base class?

Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing a common functionality to unrelated classes. Interfaces are a good choice when we think that the API will not change for a while.


1 Answers

Personally, I find abstract classes to be most useful when writing libraries or other code which interfaces between one developer and another.

One of the advantages of statically-typed languages is that when you use the wrong type, it fails early (often, as early as compile time). ABCs allow Python to gain this same advantage with dynamic typing.

If your library code duck types an object which lacks a vital method, it likely won't fail until that method is needed (which could take significant time or put resources into an inconsistent state, depending on how it's used). With ABCs, however, a missing method either isn't using the correct ABC (and fails an instanceof check) or is "validated" by the ABC.

Additionally, ABCs serve as an excellent way to document interfaces, both conceptually and, via docstrings, literally.

like image 86
Ben Blank Avatar answered Nov 02 '22 06:11

Ben Blank