Variables with cross-module usage

MRAB python at mrabarnett.plus.com
Sat Nov 28 17:36:24 EST 2009


Nitin Changlani. wrote:
> Hello everyone,
> 
> I am fairly new to Python and occasionally run into problems that are 
> almost always resolved by referring to this mailing-list's archives. 
> However, I have this one issue which has got me stuck and I hope you 
> will be tolerant enough to help em out with it!
> 
> What I want to achieve is something like the global variables in C/C++: 
> you declare them in one file and "extern" them in all the files where 
> you need to use them. I have 3 files: one.py, two.py and three.py as below:
> 
> one.py
> ----------
> a = 'place_a'
> b = 'place_b'
> x = 'place_x'
> 
> myList = [a, b, 'place_c']
> 
> ======================================================================
> 
> two.py
> ----------
> import one
> 
> def myFunc():
>     print one.x
>     print one.myList
> 
> ======================================================================
> 
> three.py
> ------------
> import one
> import two
> 
> def argFunc():
>     one.x = 'place_no_x'
>     one.a = 'place_no_a'
>     one.b = 'place_no_b'
> 
> if __name__ == '__main__':
>     two.myFunc()
>     print
>     argFunc()
>     two.myFunc()
> 
> ======================================================================
> 
> Output:
> -----------
> 'place_x'
> ['place_a', 'place_b', 'place_c']
> 
> 'place_no_x'
> ['place_a', 'place_b', 'place_c'] (*** instead of ['place_no_a', 
> 'place_no_b', 'place_c'] ***)
> 
> The last line in the output is what's baffling me. Can anyone please 
> help me know if I am doing something wrong?
> 
What's confusing you?

myList gets its value (['place_a', 'place_b', 'place_c']) when one.py is
first imported, and you never change it after that.



More information about the Python-list mailing list