persistant gloabl vars (very newbie) ?

Stef Mientki S.Mientki-nospam at mailbox.kun.nl
Thu Dec 28 10:03:35 EST 2006


Erik Johnson wrote:
>> but it's still not quit handy
>>
>> # initialization file (init1.py)
>> import time;
>> xx = 44
>>
>> # main file was
>> print xx
>> x=time.time()
>>
>> # main file should become
>> print init1.xx
>> x=init1.time.time()
>>
>> so even for the "standard" functions like "time" I've to include the
>> preceeding module "init1" :-(
> 
> 
> Ummm... does this help?
> 
> /src/python/Foo> cat init.py
> #! /usr/local/bin/python
> 
> from time import time
> xx = 44
> 
> /src/python/Foo> python
> Python 2.3.4 (#1, Feb  7 2005, 15:50:45)
> [GCC 3.3.4 (pre 3.3.5 20040809)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> from init import *
>>>> dir()
> ['__builtins__', '__doc__', '__file__', '__name__', 'time', 'xx']
>>>> xx
> 44
>>>> time
> <built-in function time>
>>>> time()
> 1167262478.6845641
>>>> xx = 42  # this does not change the init module's value!
>>>> import init
>>>> init.xx
> 44
> 
>     As Piet points out, you get a copy of variables defined in a module when
> using the from module import * syntax (as is demonstrated by the assignment
> above). (And I stand corrected on the notion that you could execute "from
> module import *" in other than module level scope.)
> 
>     If it is your intention to use those variables defined in init to
> communicate with other modules making the same sort of import, then you
> probably don't want to use  "from module import *"  syntax.  In that case,
> you can import just the module, and make assignments into that module's
> namespace. (e.g., init.xx = 3)
> 
>     If all you care about is getting some "stuff" into your global namespace
> in a convenient and repeatable way, then I think what I showed both above
> and originally is fine.
> 
thanks Erik,

I think I'm slowly getting the picture:
always use "import", which is the most unambiguous approach.
Life is sometimes difficult for a MatLab user, see my next post ;-)

Stef



More information about the Python-list mailing list