'Real' global (write var to different namespace)
Frank Sonnenburg
sonnenbu at informatik.uni-bonn.de
Wed Sep 18 10:09:02 EDT 2002
"Maarten van Hulsentop" <maarten at tccn.info> schrieb im Newsbeitrag
news:29242dfa.0209180310.94c915d at posting.google.com...
> Hi y'all
>
> I'm sorry if it's a FAQ but i honestly can't find to solution to my
> problem; i've created a 'store' (a class) to store vars using the
> (really cool) pickle classes. Now i can store a var doing:
> "mystore['varname'] = myvar" and read it again by "myvar =
> mystore['varname']". My question is if it's possible to create a
> function like 'mystore.RestoreVars()' that sets ALL the stored vars in
> the _calling_ namespace at once.
>
> Hope it's clear enough, i'm still a python newbie so excuse me if i
> used the wrong terms or if i didn't explain it enough.
>
> Thanks
>
> Maarten van Hulsentop
Maybe you will use this class prototype:
======================================================
class store:
"Storage class for arbitrary data"
def writeto(self, obj):
"Make contents of storage instance visible in obj"
obj.__dict__.update(self.__dict__)
======================================================
You have to pass the calling namespace explicitly, maybe you will see this
as a disadvantage, but it fits to python philosophy: explicit is better than
implicit.
======================================================
Examples:
1 - Instantiating of storage
>>> st = store()
>>> st.storage_var = 42
2 - Make visible in main scope
>>> import sys
>>> st.writeto(sys.modules['__main__'])
>>> dir()
['__builtins__', '__doc__', '__name__', 'st', 'storage_var', 'store', 'sys']
>>> storage_var
42
3 - Make visible in some object
>>> class c:
... pass
...
>>> o = c()
>>> st.writeto(o)
>>> dir(o)
['storage_var']
>>> o.storage_var
42
4 - Usage in instance method
>>> class cc:
... def f(self):
... st.writeto(self)
...
>>> oo = cc()
>>> oo.f()
>>> oo.storage_var
42
======================================================
Hope it is nearly what you desired -- Frank
More information about the Python-list
mailing list