简体   繁体   中英

python imported global variables immutable

I have a python module eg myModule in a subfolder and I have two files:

__init__.py :

from _auxiliary import *

_auxiliary.py :

myvar=False

def initialize():
    global myvar
    myvar=5

Now in ipython when I run:

>> import myModule
>> myModule.initialize()

the variable myModule.myvar is unchanged ie False

This does not happen if I put everything in __init__.py

Any idea on how to fix it?

Python - Visibility of global variables in imported modules

The problem is that globality is relatve to the module in question.

You could import _auxiliary directly:

from mymodule import _auxiliary
_auxiliary.initialize()
print _auxiliary.myvar

The short answer is that globals in Python are global to a module, not across all modules. (This is a bit different from other languages and can cause some confusion).

An easy way to solve this (there are some others) is to define a getter method in the original module, in your case:

_myvar=False

def initialize():
    global _myvar
    _myvar=5

def myvar():
    global _myvar
    return _myvar

So you can access the _myvar instance with the correct value from whatever module.

import myModule
myModule.initialize()
print("myvar value:", myModule.myvar())

Previous code will show "myvar value: 5"

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