A startup puzzle

Steve Holden sholden at holdenweb.com
Mon Sep 29 19:24:51 EDT 2003


"Edward K. Ream" <edreamleo at charter.net> wrote in message
news:vnh8uh5j8e3i44 at corp.supernews.com...
> > Perhaps using a proxy object...might work:
>
> Great idea!  Some complications:
>
> 1. Sometimes the test "if not realApp:" causes unbounded recursion.  To
> avoid any possibility of this happening the startup code just creates the
> app object before any code actually uses the app proxies.  This is easily
> done.
>
> 2. A __call__ method in the proxy allows the code to use either app().x or
> app.x.
>
> In short, the following pattern appears like it will work in all my
modules:
>
> from leoGlobals import *
> app = leoProxy() # leoProxy defined in leoGlobals
> # Now the code can reference either app.x or app().x.
>
> To do this, I use the following code:
>
> gApp = None # Set before any reference to proxy.
> class leoProxy:
>   def __getattr__(self,attr):
>     return getattr(gApp,attr)
>   def __call__(self):
>     return gApp
>
> Many thanks for this great idea.
>

I've followed this thread, and I'm having trouble understanding why nobody's
suggested using Alex martelli's "borg" pattern, which he originally called a
"statel;ess proxy", where all objects of a given type share the same state
information. Sounds to me that's what you really want, no?

This would mean that in leo_global you would have something like this:

leo_global.py:
-------------
class Borg(object):
    _state = {}
    def __new__(cls, *p, **k):
        self = object.__new__(cls, *p, **k)
        self.__dict__ = cls._state
        return self


module1.py
-------------
from leo_global import Borg

myborg = Borg()
myborg.var1 = "This is var 1"

import module2

print "Module 1's borg has var1 =", myborg.var1, id(myborg.var1)
print "Module 1's borg has var2 =", myborg.var2, id(myborg.var2)


 module2.py:
-------------
from leo_global import Borg

myborg = Borg()
myborg.var2 = "This is var 2"

print "Module 2's borg has var1 =", myborg.var1, id(myborg.var1)
print "Module 2's borg has var2 =", myborg.var2, id(myborg.var2)

The result of all this appears to be what you want: a simple way of creating
an easily-referenced shared state. Vide:

C:\Steve\Projects\Python>python module1.py
Module 2's borg has var1 = This is var 1 7766584
Module 2's borg has var2 = This is var 2 8008928
Module 1's borg has var1 = This is var 1 7766584
Module 1's borg has var2 = This is var 2 8008928

regards
-- 
Steve Holden                                  http://www.holdenweb.com/
Python Web Programming                 http://pydish.holdenweb.com/pwp/







More information about the Python-list mailing list