There's GOT to be a better way!

Steve Holden steve at holdenweb.com
Fri Mar 4 00:43:36 CET 2005


Earl Eiland wrote:
> On Thu, 2005-03-03 at 15:11, Steve Holden wrote:
> 
>>Earl Eiland wrote:
>>
>>>I'm writing my first program where I call custom modules.  The 'global'
>>>command doesn't seem to apply, so how do I change a variable internally
>>>in a module without passing it down n layers, and then back out again?
>>>
>>
>>You are correct in assuming that global isn't what you want - it really 
>>means "global to the module namespace in which it appears".
>>
>>However, if two separate pieces of code can both reference the same 
>>module then one can set an attribute in the module and the other can 
>>reference it. Don't forget that when you import a module its name 
>>becomes global within the importing module. Since a module is just a 
>>glorified namespace, anything that can reference the module can read 
>>and/or set that module's attributes.
>>
>>a.py:
>>
>>import something
>>something.x = "A value"
>>
>>b.py:
>>
>>import something
>>print something.x
>>
>>will print "A value" as long as a is imported before b.
> 
> Right.  That part I figured out.  How does one function in an imported
> module access a variable in the same module?
> 
> module.py
> 	def A():
                 global test
> 		test = 1
> 		for x in range(10): B()
>  	
> 	def B():
                 global test
> 		test = test + 1
> 
> 
> main.py
> 	import module
> 	module.A()
         print module.test
> 
> 
> This will fail, unless test is passed and returned.
> 

regards
  Steve
-- 
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005                      http://www.pycon.org/
Steve Holden                           http://www.holdenweb.com/



More information about the Python-list mailing list