Imported globals?

Gary Herron gherron at islandtraining.com
Fri Jul 27 17:56:27 CEST 2007


Valentina Vaneeva wrote:
> Hi,
>
> I'm new to Python and I've found something in its interpreter that I 
> don't quite understand, and I don't really know how to correctly 
> formulate a search query. Here's the question.
>
> If we have a file module_a.py with the following content:
>
> |	#!/usr/bin/env python
> |
> |	value = 'initial'
> |
> |	def change_value():
> |		global value
> |		value = 'changed'
>
> and a file module_b.py:
>
> |	#!/usr/bin/env python
> |
> |	from module_a import value, change_value
> |
> |	change_value()
> |	print value
> 	
> Then, if we run module_b.py, it will print "initial". However, if one 
> adds to the end of module_a.py this line:
>
> |	change_value()
>
> The script module_b.py will print "changed".
>
> It seems that in the first case change_value() called in module_b.py 
> ignores the global statement. Is it so? Why? What happens in the second 
> case? I really don't get it.
>   
In Python, there are not any truly "global" variables as you're thinking 
of them.   Instead, each module has it's own global space.  You are 
tripping over the fact that module_a and module_b have their own 
separate global spaces.

The variable "value" is global in module_a, and "change_value" will 
always refer to that variable.

However, in module_b, when you  
     from module_a import value, change_value
you have created two new variables global to module_b that references 
values from the other module.
Now running change_value (which changes "value" in module_a has no 
affect on the version of "value" in module_b.   Your print is then 
printing value from module_b -- the unchanged version.

If you truly want to examine value in module_a, the you have to access it as
    import module_a
    module_a.change_value()
    print module_a.value

You can do both
    import module_a
    from module_a import change_value
but that's probably confusing and generally considered a bad idea.

Ideas: 

1 If you want module_a to manage such a global variable, you could 
include functions for getting, and setting it, as well as your function 
for changing it's value.

2. You could also dispense with use of global values -- various OOP 
techniques could help there.

Gary Herron



> Thanks!
>
> Cheers,
> 	Valia
>
>   




More information about the Python-list mailing list