简体   繁体   中英

Python 3: The visibility of global variables across modules

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM