By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,760 Members | 1,137 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,760 IT Pros & Developers. It's quick & easy.

Re: Help with Borg design Pattern

P: n/a
Le Saturday 28 June 2008 03:47:43 Casey McGinty, vous avez écrit*:
On Fri, Jun 27, 2008 at 3:21 PM, Casey McGinty <ca***********@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
Jun 28 '08 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.