Here is an example of an interface as seen in the "Fluent Python" book:
from abc import ABCMeta, abstractmethod
class IStream(metaclass=ABCMeta):
@abstractmethod
def read(self, maxbytes=-1):
pass
@abstractmethod
def write(self, data):
pass
A bit further in the book, one can read that "code that explicitly checks for this interface could be written as follows":
def serialize(obj, stream):
if not isinstance(stream, IStream):
raise TypeError('Expected an IStream")
My question is: why would I need such isinstance
checks? Is it for cases when stream
might be an instance of a class that does not inherit from IStream
?
Otherwise, my understanding is that it should not be needed, because if the instance that gets passed as stream
would not satisfy the IStream
interface (by inheriting from the ABC), it would not be allowed to instantiate before it even gets passed:
class Stream(IStream):
def read(self):
pass
def WRITE(self):
pass
stream = Stream()
Traceback (most recent call last): File "c:\python projects\test.py", line 18, in stream = Stream() TypeError: Can't instantiate abstract class Stream with abstract method write