Help with Borg design Pattern
Maric Michaud
maric at aristote.info
Fri Jun 27 23:25:54 EDT 2008
Le Saturday 28 June 2008 03:47:43 Casey McGinty, vous avez écrit :
> On Fri, Jun 27, 2008 at 3:21 PM, Casey McGinty <casey.mcginty at gmail.com>
>
> wrote:
> > Hi,
> >
> > I'm trying to implement a simple Borg or Singleton pattern for a class
> > that inherits from 'dict'. Can someone point out why this code does not
> > work?
> >
> > class MyDict( dict ):
> > __state = {}
> > def __init__(self):
> > self.__dict__ = self.__state
> >
> > a = MyDict()
> > a['one'] = 1
> > a['two'] = 2
> >
> > print a
> > print MyDict()
>
Well, it works !
>>>[156]: class MyDict( dict ):
__state = {}
def __init__(self):
self.__dict__ = self.__state
.....:
.....:
>>>[160]: MyDict().toto = 5
>>>[161]: MyDict().toto
...[161]: 5
but the __dict__ attribute is the container of attributes of an instance,
which are not used in the underlying implementation of dictinnaries.
> This looks like a good solution:
>
> class MyDict( dict ):
> def __new__(cls,*p,**k):
> if not '_instance' in cls.__dict__:
> cls._instance = dict.__new__(cls)
> return cls._instance
Yes it is, but it's rather unneeded in Python, we prefer simply create a
module level dictionnary, these tricks are used in language like C++ or Java.
In python :
mymodule.py :
ModuleOptions = {}
othermodule.py :
import mymodule
mymodule.ModuleOptions['Verbose'] = True
or if you think encapsulation is important :
mymodule.py :
_ModuleOptions = {}
def get_option(opt) :
return _ModuleOptions[opt]
....
And you're done.
--
_____________
Maric Michaud
More information about the Python-list
mailing list