[PyQt] thoughts about dip interfaces and python abstract base classes

Darren Dale dsdale24 at gmail.com
Sun Mar 13 20:14:15 GMT 2011


On Sun, Mar 13, 2011 at 3:01 PM, Darren Dale <dsdale24 at gmail.com> wrote:
> I've been learning about python's abstract base classes at
> http://www.python.org/dev/peps/pep-3119/ and
> http://docs.python.org/py3k/library/abc.html . The PEP mentions that
> there is considerable overlap between ABCs and interfaces, and I'm
> rereading the dip documentation on interfaces now. If I understand
> correctly, dip's "implements" decorator is similar (perhaps based on)
> python's abstract base class "register" class method. Is it ever the
> case that dip classes actually subclass a dip interface, as python
> classes would subclass one or more abstract base class?

It also occurs to me that, if Interface were/is based on abstract base
classes with properties and methods decorated with @abstractmethod,
dip classes that actually subclass such an Interface would benefit
from python's built-in checks that prevent instantiation of an object
that has not overridden all the necessary methods declared in the
interface:

from dip.model import Interface, Str

class IDownload(Interface):

    # The URL to download from.
    url = Str()

    @url.default
    @abstractmethod
    def url(self):
        pass

    @abstractmethod
    def download(self):
        """ Download the file. """


class Download(Model, IDownload)

    @IDownload.url.default
    def url(self):
        return ''

    def download(self):
        """ Download the file using urllib. """


Then if we have a class that needs to be adapted to IDownload:

class FileDownloader:

    def __init__(self, target_file):

        # Save the URL for later.
        self.target_file = target_file

    def get_file(self):
        # Download the file self.target_file


The "adapt" decorator could register the adapter class with the
appropriate Interfaces that it identifies in
FileDownloaderIDownloadAdapter's superclasses:

from dip.model import adapt, Adapter, DelegatedTo

@adapt(FileDownloader)
class FileDownloaderIDownloadAdapter(Adapter, IDownload):
    """ This adapts FileDowloader to IDownload. """

    url = DelegatedTo('adaptee.target_file')

    def download(self):
        """ Implement IDownload.download(). """

        return self.adaptee.get_file()

This way, Interfaces are more closely unified with python's abstract
base classes, one can be certain that a class deriving from an
interface has fully implemented it, while still benefiting from dip's
adaptation.

Cheers,
Darren


More information about the PyQt mailing list