Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python global variable insanity

Tags:

python

You have three files: main.py, second.py, and common.py

common.py

#!/usr/bin/python
GLOBAL_ONE = "Frank"

main.py

#!/usr/bin/python
from common import *
from second import secondTest

if __name__ == "__main__":
    global GLOBAL_ONE
    print GLOBAL_ONE #Prints "Frank"
    GLOBAL_ONE = "Bob"
    print GLOBAL_ONE #Prints "Bob"

    secondTest()

    print GLOBAL_ONE #Prints "Bob"

second.py

#!/usr/bin/python
from common import *

def secondTest():
    global GLOBAL_ONE
    print GLOBAL_ONE #Prints "Frank"

Why does secondTest not use the global variables of its calling program? What is the point of calling something 'global' if, in fact, it is not!?

What am I missing in order to get secondTest (or any external function I call from main) to recognize and use the correct variables?

like image 274
Ankh Avatar asked Jun 25 '10 15:06

Ankh


1 Answers

global means global for this module, not for whole program. When you do

from lala import *

you add all definitions of lala as locals to this module.

So in your case you get two copies of GLOBAL_ONE

like image 107
nkrkv Avatar answered Sep 22 '22 04:09

nkrkv