[Tutor] Borg di borg di borg (or: Swedish chef)

eryksun eryksun at gmail.com
Mon Sep 24 19:01:30 CEST 2012

On Mon, Sep 24, 2012 at 6:02 AM, Albert-Jan Roskam <fomcl at yahoo.com> wrote:
> I have three classes, Generic, Test and Test2. Generic contains a load
> method that loads a file. This may only be done once, as a
> file_read_open error is returned if the file is open already and an
> attempt is made to re-open it. The file may be opened from Test or Test2.

What's the context here? Is "file_read_open error" an error code
returned by a library? If so, I'd pass it on by raising an exception
instead of masking the error.

As to the Borg pattern, it seems to me you don't actually need a
'Borg' base class. But if you do, then you probably also want to
override _state with a new dict for each subclass. You can do this
automatically with a custom descriptor, a metaclass, or even a simple
property like the following:

    class Borg(object):
        _all_state = {}

        def __init__(self):
            self.__dict__ = self._state

        def _state(self):
            return self._all_state.setdefault(self.__class__, {})

    class Generic(Borg):

        def __init__(self):
            super(Generic, self).__init__()
            self.loaded = None

        def load(self, filename):
            """ Only one file at a time may be opened, or else
            there will be an open-read error"""
            if self.loaded is None:
                self.loaded = open(filename)
            return self.loaded

More information about the Tutor mailing list