Hello, if one finds interfaces useful in Python (>=3.8) and is convinced that static type-checking is a must, then why not ditch ABC and always use Protocols? I understand that the fundamental idea of a protocol is slightly different from an interface, but in practice, I had great success replacing abc's with Protocols without regrets.
With abc you would write (https://docs.python.org/3/library/abc.html) :
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def eat(self, food) -> float:
passWhereas with Protocols it's gonna be (good tutorial):
from typing import Protocol
class Animal(Protocol):
def eat(self, food) -> float:
...Scores in my subjective scoring system :)
| Capability | ABC | Protocols |
|---|---|---|
| Runtime checking | 1 | 1 (with a decorator) |
| Static checking with mypy | 1 | 1 |
Explicit interface (class Dog(Animal):) | 1 | 1 |
Implicit interface with duck-typing (class Dog:) | 0.5 (kind of with register, but it doesn't work with mypy yet) | 1 |
Default method implementation (def f(self): return 5) | -1 (implementations shouldn't be in the interfaces) | -1 (same, and mypy doesn't catch this) |
| Callback interface | 0 | 1 |
| Number of code lines | -1 (requires ABC inheritance and abstracmethod for every method) | 0 (optionalProtocol inheritance) |
| Total score | 1.5 | 4 |
So I do not quite see why one should ever use ABC except for legacy reasons. Other (IMHO minor) points in favour of ABC I've seen were about interactions with code editors.
Did I miss anything?
I put more detailed arguments into a Medium. There are many tutorials on using Protocols, but not many on ABC vs Protocols comparisons. I found a battle of Protocols vs Zope, but we are not using Zope, so it's not so relevant.
Videos
New in Python 3.8:
Some of the benefits of interfaces and protocols are type hinting during the development process using tools built into IDEs and static type analysis for detection of errors before runtime. This way, a static analysis tool can tell you when you check your code if you're trying to access any members that are not defined on an object, instead of only finding out at runtime.
The typing.Protocol class was added to Python 3.8 as a mechanism for "structural subtyping." The power behind this is that it can be used as an implicit base class. That is, any class that has members that match the Protocol's defined members is considered to be a subclass of it for purposes of static type analysis.
The basic example given in PEP 544 shows how this can be used.
Copyfrom typing import Protocol
class SupportsClose(Protocol):
def close(self) -> None:
# ...
class Resource:
# ...
def close(self) -> None:
self.file.close()
self.lock.release()
def close_all(things: Iterable[SupportsClose]) -> None:
for thing in things:
thing.close()
file = open('foo.txt')
resource = Resource()
close_all([file, resource]) # OK!
close_all([1]) # Error: 'int' has no 'close' method
Note: The typing-extensions package backports typing.Protocol for Python 3.5+.
In short, you probably don't need to worry about it at all. Since Python uses duck typing - see also the Wikipedia article for a broader definition - if an object has the right methods, it will simply work, otherwise exceptions will be raised.
You could possibly have a Piece base class with some methods throwing NotImplementedError to indicate they need to be re-implemented:
Copyclass Piece(object):
def move(<args>):
raise NotImplementedError(optional_error_message)
class Queen(Piece):
def move(<args>):
# Specific implementation for the Queen's movements
# Calling Queen().move(<args>) will work as intended but
class Knight(Piece):
pass
# Knight().move() will raise a NotImplementedError
Alternatively, you could explicitly validate an object you receive to make sure it has all the right methods, or that it is a subclass of Piece by using isinstance or isubclass.
Note that checking the type may not be considered "Pythonic" by some and using the NotImplementedError approach or the abc module - as mentioned in this very good answer - could be preferable.
Your factory just has to produce instances of objects having the right methods on them.
Hi everyone. Last time I shared a post about Interface programming using abs in Python, and it got a lot of positive feedback—thank you!
Several people mentioned protocols, so I wrote a new article exploring that topic. In it, I compare protocols with abstract base classes and share my thoughts and experiences with both. You can check it out here: https://www.tk1s.com/python/protocols-vs-abstract-base-classes-in-python Hope you'll like it! Thanks!
There is no such built-in ABC. In fact, every class has this method inherited from object:
The default implementation defined by the built-in type object calls object.repr().
See docs.
In [1]: class Foo: pass
In [2]: str(Foo())
Out[2]: '<__main__.Foo object at 0x7fcf10e219f0>'
In [3]: print(Foo())
<__main__.Foo object at 0x7fcf10e23d00>
In [4]: print(Foo().__str__())
<__main__.Foo object at 0x7fcf10e20d60>
In [5]: print(Foo().__repr__())
<__main__.Foo object at 0x7fcf10e20af0>
In [6]: object().__repr__()
Out[6]: '<object object at 0x7fcf119c6810>'
In [7]: object().__str__()
Out[7]: '<object object at 0x7fcf119c67c0>'
There's no such a builtin abstract class, but you can enforce those requirements.
from abc import ABC, abstractmethod
class Required(ABC):
@abstractmethod
def __str__(self) -> str:
...
@abstractmethod
def __hash__(self) -> int:
...
@abstractmethod
def __eq__(self, other) -> bool:
...
>>> class Impl(Required): ...
>>> i = Impl()
TypeError: Can't instantiate abstract class Impl with abstract methods __eq__, __hash__, __str__
Also, you could check a specific structural subtyping for equality at runtime, and return a TypeError if it's not the case (but it may not be a best practice):
from typing import Protocol, runtime_checkable
@runtime_checkable
class HasValue(Protocol):
value: int
class Impl(Required):
# also define __str__ and __hash__
@property
def value(self):
return 42
def __eq__(self, other):
if not isinstance(other, HasValue):
raise TypeError
return self.value == other.value
class Valued:
value = 42
class NotValued:
...
>>> i = Impl()
>>> v = Valued()
>>> n = NotValued()
>>> i == v # both have self.value
True
>>> v == n # self.value not enforced
False
>>> i == n # self.value enforced
TypeError