Reputation: 3494
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
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
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