luke1985
luke1985

Reputation: 2354

Why global value doesn't change when reading from another module?

I have three files:

globals.py:

value = None

reader.py:

from globals import *

def read_global():
    print(value)

changer.py:

from globals import *
from reader import *

def change_global():
    global value
    value = 1


change_global()
read_global()

I would expect the call to "read_global" would print 1, but the value None is printed.

Why is that the case? Why the new value set in "change_global" doesn't print?

Upvotes: 0

Views: 81

Answers (2)

luke1985
luke1985

Reputation: 2354

I've been reading about modules in the Python documentation and it states:

Each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module. Thus, the author of a module can use global variables in the module without worrying about accidental clashes with a user’s global variables. On the other hand, if you know what you are doing you can touch a module’s global variables with the same notation used to refer to its functions, modname.itemname.

This implicates that the global symbol table is not shared between modules.

Upvotes: 0

Dafa Wiratama
Dafa Wiratama

Reputation: 57

Change your import into

changer.py:

from reader import *
import globals as g


def change_global():
    g.value = 1


change_global()
read_global()
print(g.value)

reader.py:

import globals as g

def read_global():
    print(g.value)

globals.py:

value = None

I think when you call value in the change_global function you are not calling the global variable you declare in global.py but creating new local variable inside the function so when you set the import alias into g will make sure you call/set the right one (variable)

Upvotes: 1

Related Questions