Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the Abstract Base Class register method actually do?

I am confused about the ABC register method.

Take the following code:

import io
from abc import ABCMeta, abstractmethod

class IStream(metaclass=ABCMeta):
    @abstractmethod
    def read(self, maxbytes=-1):
        pass
    @abstractmethod
    def write(self, data):
        pass

IStream.register(io.IOBase)

f = open('foo.txt')

isinstance(f, Istream) # returns true

When you register io.IOBase what exactly happens? Are you saying that IOBase class can only have methods defined by Istream ABC class going forward? What is the benefit of ABC registering other classes?

like image 761
pablowilks2 Avatar asked Mar 23 '26 06:03

pablowilks2


1 Answers

It simply makes issubclass(io.IOBase, IStream) return True (which then implies that an instance of io.IOBase is an instance of IStream). It is up to the programmer registering the class to ensure that io.IOBase actually conforms to the API defined by IStream.

The reason is to let you define an interface in the form of IStream, and let you indicate that a class that may not have actually inherited from IStream satisfies the interface. Essentially, it is just formalized duck typing.

like image 192
chepner Avatar answered Mar 25 '26 20:03

chepner