How to give a global variable to a function which is in a module?

Terry Reedy tjreedy at udel.edu
Wed Oct 1 16:21:21 EDT 2008


Kurda Yon wrote:
> Hi,
> 
> I would like to declare a global variable, which is seen to a
> particular function. If I do as the following it works:
> 
> x = 1
> def test():
>   global x
>   print x
>   return 1

If you are just reading x, the global statement does nothing and is not 
needed.

> However, it does not helps since my function is in a separate file. In
> other words I have a main program which has the following structure:
> 
> from test import test
> x = 1
> y = test()
> 
> and I have a test.py file which contains the "test" function:
> def test():
>   global x
>   print x
>   return 1
> 
> In this case the test does not see the global variable x. How can I
> make the x to be visible?

'Global' means 'global to the current module in which the global 
statement appears.  Yes this is confusing.  'Modular' would be more 
exact, but 'global' goes back to before Python when there were no 
separate modules connected together.

Either pass x to the function (probably best) or put x into the imported 
module with 'test.x = 1".

Terry Jan Reedy




More information about the Python-list mailing list