Re: Help with Borg design Pattern

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Maric Michaud

    Re: Help with Borg design Pattern

    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@ 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__(cl s)
    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.Module Options['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
Working...