Pregunta

I came across some weird behaviour about how Python handles global (module) variables and the global keyword.

Module 1:

g = None

def set_g_up():
    global g
    g = "foo"

set_g_up()
print g

Module 2:

from module_1 import *

set_g_up()
print g

Module 1 prints, as expected, "foo".
Module 2 prints None!

What? It’s the same object! Or, at least, I expect it to be.

¿Fue útil?

Solución

Each module has its own global name scope. By importing everything via * from another module, you create copies (additional references to the values) of the globals of the other module into your own module.

Use qualified names in order to prevent this from happening:

import module_1

module_1.set_g_up()
print module_1.g

There is no way to access the same variable by calling it g if you in fact mean the variable module_1.g. All you can make happen is that both variables contain the same value (makes only sense for lists, objects and other mutables).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top