Python Forum
Right way to implement interfaces - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Right way to implement interfaces (/thread-37204.html)



Right way to implement interfaces - yossiy123 - May-12-2022

Hi all!

There is a right way to implement interfaces?
I read about ABC but I heard it going to be deprecated so I want to know if there is other way for it.

Thanks!


RE: Right way to implement interfaces - Gribouillis - May-12-2022

Where have you read that ABCs are going to be deprecated? The only news I read about this is that importing some ABCs from module collections is deprecated, for example
from collections import Sequence
is deprecated and one should use
from collections. abc import Sequence
yossiy123 Wrote:There is a right way to implement interfaces?
This question suggests that you may come from a Java background or a similar language where interfaces play a major role. This is not so in Python and interfaces are often just a gentlemen's agreement that a class will possess such and such method that behave in a certain way. Python is much more informal.

For example the Iteration protocol supposes that a class must have an __iter__ method that returns an iterable which in turn have an __iter__ and a __next__ method with appropriate semantics. Classes that implement this protocol don't need to declare explicitly that they implement the iteration protocol and that is the way many of these classes work. These classes can also declare that they are «subclasses» of the ABCs collections.abc.Iterable and collections.abc.Iterator respectively.

As far as I know, Abstract Base Classes are the still correct way to have your class explicitly declare that they implement an interface.