[Tutor] Borg di borg di borg (or: Swedish chef)
Peter Otten
__peter__ at web.de
Mon Sep 24 12:38:33 CEST 2012
Albert-Jan Roskam wrote:
> Hi Pythonistas,
>
> 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. After a lot of
> playing with a "counter" class variable, I realized this may be a
> legitimate use case for the Borg pattern
> (http://code.activestate.com/recipes/66531). Is the code below the right
> way to apply the Borg pattern?
What do you gain from that complexity? Even
assert b1.load() is b2.load()
will fail. So why not keep it simple?
_file = None
def load_file():
global _file
if _file is None:
_file = open(somefile)
return _file
(if you are using multiple threads you have to add a lock)
Of course you can bypass this "safety" measure by doing
open(somefile)
anywhere in your code, so it is more like a gentleman's agreement between
you and yourself not to tread over the red line.
More information about the Tutor
mailing list