Resource Python Interfaces: Choose Protocols Over ABC
https://levelup.gitconnected.com/python-interfaces-choose-protocols-over-abc-3982e112342e7
u/Workaphobia Feb 12 '23
I haven't worked in python in some time. Sounds like protocols are similar to Go's concept of interfaces? I.e. structural typing.
2
20
u/jkajala Feb 12 '23 edited Mar 02 '23
... And 9 out of 10 cases don't use either. Most likely you're a Java programmer who is wondering where all your boilerplate code went when you switched to Python 🙂
1
3
u/FailedPlansOfMars Feb 12 '23
Protocols just make your duck typing explicit. Base classes are helpful but id avoid using them in typing.
3
u/oxlade39 Feb 12 '23
For me this misses the biggest benefit of using ABC over Protocol and the reason I don’t really bother with them.
IDE support. I use pycharm so this won’t apply to all. I can easily view and inspect all implementations of my interfaces (ABCs). This is a really important dimension of navigating and understanding a reasonable size code base.
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.