global variables or inheritence

Gordon McMillan gmcm at hypernet.com
Wed Apr 26 17:17:57 EDT 2000


Thomas Rasmussen  wrote:
> >>>>> "Jeff" == Jeff Massung <jmassung at magpiesystems.com> writes:
> 
>   Jeff> Sorry if I get this wrong... but I thought you'd just
>   import Jeff> your other file.
> 
>   Jeff> Example:
> 
>   Jeff> # File1.py myVar = 2
> 
> 
>   Jeff> # File2.py import File1 print File1.myVar #should print 2
> 
> Well that was also what I thought, but the following program wont
> execute: testprog1.py: import os, sys, string, testprog2 def
> main():
>     print 'hello'
>     myvar = 2
>     testprog2.second()
> if __name__ == '__main__':
>     main()
> 
> testprog2.py:
> import os, sys, string, testprog1
> def second():
>     print testprog1.myvar
> if __name__ == '__main__':
>     print 'nope'

Circular imports are fine in Python (well, there are some 
gotchas). Your problem here is that "import testprog1" is 
creating a new instance of testprog1, which is not the same 
one you're executing (which is known as "__main__").

Add the line "global myvar" inside testprog1.main. Now 
execute "import testprog1" from the interactive prompt (or 
another script) and testprog2 will work as expected.

If you really want to get to variables in the executing script, 
you need to "import __main__" in the submodule, and 
schedule yourself for a severe spanking.

> and then I execute python testprog1.py and get the following
> error:
> 
> 22:03 simpsons at lada% python testprog1.py                         
>      ~/python hejsa Traceback (innermost last):
>   File "testprog1.py", line 7, in ?
>     main()
>   File "testprog1.py", line 5, in main
>     testprog2.second()
>   File "testprog2.py", line 3, in second
>     print testprog1.myvar
> AttributeError: myvar
> 
> :-(
> 
> Thomas
> 
> -- 
> KOM Network student helper
> 
> "To alcohol! The cause of - and solution to - all of life's
> problems!" -- Homer Simpson --
> http://www.python.org/mailman/listinfo/python-list



- Gordon




More information about the Python-list mailing list