12

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?

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.