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!
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.