global vars across modules

Kiuhnm kiuhnm03.4t.yahoo.it
Sun Apr 22 18:13:19 EDT 2012


On 4/22/2012 23:08, 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'.

Actually, that doesn't work. I never used "external variables" in Python 
and I thought "from file_1 import *" worked differently. What a 
surprise. It makes sense though.
"Import" imports values, not variables.

Anyway, you don't need all this.

Kiuhnm



More information about the Python-list mailing list