Python 3: The visibility of global variables acros

2019-09-19 04:03发布

问题:

Similar questions have been asked before:

here, here and here, and I am aware of these.

Say you have 2 modules where one has global variables that you want to read from in another module. Is there a way to make these accessible across modules without having to refer to them as module.variable each time?

Example:

modulea.py:

import moduleb
from moduleb import *

print("A String: " + astring)
print("Module B: " + moduleb.astring)
afunction()
print("A String: " + astring)
print("Module B: " + moduleb.astring)

moduleb.py:

astring = "dlroW olleH"

def afunction():
    global astring
    astring = "Hello World"

The output is

A String: dlroW olleH
Module B: dlroW olleH
A String: dlroW olleH
Module B: Hello World

suggesting that by using "from module import * " the global variables are copied rather than referenced.

Thanks in advance for any help.

回答1:

from module import * binds the objects in module to like named variables in the current module. This is not a copy, but the addition of a reference to the same object. Both modules will see the same object until one of them rebinds the object. Modifying a mutable object doesn't rebind the variable so an action such as appending to a list is okay. But reassigning the the variable does rebind it. Usually the rebind is straight forward:

myvar = something_else

But sometimes its not so clear

myvar += 1

For immutable objects such as int or str, this rebinds the variable and now the two modules have different values.

If you want to make sure you always reference the same object, keep the namespace reference.