global vars across modules

Dave Angel d at davea.name
Sun Apr 22 17:32:13 EDT 2012


On 04/22/2012 05:08 PM, Kiuhnm wrote:
> On 4/22/2012 21:39, mamboknave at gmail.com wrote:
>> I need to use global var across files/modules:
>>
>> # file_1.py
>> a = 0
>> def funct_1() :
>>      a = 1    # a is global
>>      print(a)
>>
>>
>> # file_2.py
>> from file_1 import *
>> def main() :
>>     funct_1()
>>     a = 2    # a is local, it's not imported
>>     print(a)
>
> You just forgot to declare 'a' as global inside your functions.
>
> # file_1.py
> a = 0
> def funct_1() :
>     global a
>     a = 1    # a is global
>     print(a)
>
>
> # file_2.py
> from file_1 import *
> def main() :
>     global a
>     funct_1()
>     a = 2       # a is global
>     print(a)
>
> When you write 'a = 1' and 'a = 2' you create local variables named
> 'a' local to your functions, unless you specify that you're referring
> to a global variable by declaring 'a' as 'global'.
>
> Kiuhnm

That's only a small part of his problem.  The bigger problem is trying
to make a single name refer to the same value across modules.  Once he
reassigns, as in a=2, he breaks the connection, and the new value is no
longer reflected in the file_1 module.

However, now that he's completely restated the problem as saying that
the imported value is mutable, and that he doesn't intend to reassign
it, just mutate it, it's quite solvable.

Of course, even better is Roy Smith's response.  After all, why should
he try to make it a global of any kind. Just return the value where needed.



-- 

DaveA




More information about the Python-list mailing list