[Tutor] Borg di borg di borg (or: Swedish chef)
Albert-Jan Roskam
fomcl at yahoo.com
Wed Sep 26 09:56:33 CEST 2012
---- Original Message -----
> From: eryksun <eryksun at gmail.com>
> To: Albert-Jan Roskam <fomcl at yahoo.com>
> Cc: Python Mailing List <tutor at python.org>
> Sent: Monday, September 24, 2012 7:01 PM
> Subject: Re: [Tutor] Borg di borg di borg (or: Swedish chef)
>
> 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.
Hi, sorry for the late reply. Yes, this is an error by a library. Good point. I made
an error class and now check all error codes and raise an error if these are unequal
to 0.
> 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
>
> @property
> 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
Woaaah, nice! Took me a while to digest this. I've never really gotten the hang of decorators, but property() seems useful.
Decorators always seem so Python-specific; I think I intuitively prefer a solution that is more language-agnostic.
Regarding the Borg: doesn't this version (a dictionary with another dictionary as its key) defeat its purpose? Isn't it "we are
one" instead of "we are several" (one of each subclass). Btw, I subclassed from Borg to make it more explicit I was using the
Borg pattern.
Thanks!!
More information about the Tutor
mailing list