r/Python • • Feb 12 '23

Resource Python Interfaces: Choose Protocols Over ABC

https://levelup.gitconnected.com/python-interfaces-choose-protocols-over-abc-3982e112342e
64 Upvotes

20 comments sorted by

View all comments

138

u/[deleted] Feb 12 '23

Protocols and abstract classes are not interchangeable. You cannot simply choose one over the other. There is a substantial difference: abstract class ensures that an implementation meets certain requirements when a subclass is declared, while protocol checks if an instance meets certain requirements when it's being used. They are different in the same way as "They are of the same kind" and "There are things that both of them can do".

Please, don't confuse people with such articles.

5

u/[deleted] Feb 12 '23

I'm not sure if it was the author's point, but IMO subclassing and by virtue of that, abstract classes are bad patterns.

Using composition + protocols leads to more, but much more flexible, code.

8

u/[deleted] Feb 12 '23

Abstractions are great and mostly harmless. There is a point that inheritance from concrete classes should be avoided. That's totally valid.

3

u/Smallpaul Feb 12 '23

I have definitely found cases where subclassing seemed like the right mechanism.

The "protocol" has six methods, but 90% of the time 4 of the six are identical to default implementations. 10% of the time you might want to override one of those 4.

This isn't for generic modelling. It's for swappable plugin-system-like stuff.

I've found cases where subclassing is chef's kiss. But it can absolutely be overused and usually is.