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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With