On Fri, Jun 27, 2008 at 3:21 PM, Casey McGinty <ca***********@gmail.com>Well, it works !
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()
__state = {}>>>[156]: class MyDict( dict ):
def __init__(self):
self.__dict__ = self.__state
.....:
.....:
>>>[160]: MyDict().toto = 5
...[161]: 5>>>[161]: MyDict().toto
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:Yes it is, but it's rather unneeded in Python, we prefer simply create a
class MyDict( dict ):
def __new__(cls,*p,**k):
if not '_instance' in cls.__dict__:
cls._instance = dict.__new__(cls)
return cls._instance
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