tyrondis
tyrondis

Reputation: 3494

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?

Upvotes: 12

Views: 2257

Answers (2)

Ben Blank
Ben Blank

Reputation: 56572

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.

Upvotes: 6

Olivier Verdier
Olivier Verdier

Reputation: 49156

AFAIK, the standard practice has been to use the NotImplementedError exception for unimplemented abstract methods.

But I believe ABC might be considered pythonic, since it is now part of the Python standard library.

Upvotes: 1

Related Questions