当前位置: 动力学知识库 > 问答 > 编程问答 >

Python: Visibility of module-level variable depends of code using it

问题描述:

config.py

import json

import os

myfolder = os.path.dirname(os.path.realpath(__file__))

configfile = os.path.join(myfolder, '../appconfig.json')

appconfig = None

def get_config():

if myfolder is None:

return myfolder

if appconfig is not None:

return appconfig

else:

#load the config

try:

with open(configfile) as json_data:

c = json.load(json_data)

appconfig = c

return c

except Exception, e:

raise Exception("Cannot load config file %s : %s"%(configfile, `e`))

Now import it and use it:

tmp.py

import config

config.get_config()

python tmp.py

Traceback (most recent call last):

File "tmp.py", line 2, in <module>

config.get_config()

File "D:\projects\flask_ndc\lib\config.py", line 12, in get_config

if appconfig is not None:

UnboundLocalError: local variable 'appconfig' referenced before assignment

Comment out line 18 in config.py

 #appconfig = c

Now the code works - (but of course without saving the content in the global variable)

Can somebody explain why the python interpreter is not able to see that the assignment of appconfig in line 18 refers to the module-global variable appconfig, declared in line 7 ????

网友答案:

You problem is this line:

appconfig = c

It means define a new name in locals of function get_config. So when Interpreter run this line:

if appconfig is not None:

It treat name "appconfig" as a local variable, but it is not defined in former local codes, so the exception cames out.

If you don't assign any thing to appconfig in function get_config, the Interpreter considers appconfig as a enclosing name, and use appconfig in module-level.

If you want to assign value to appconfig in function, just use "global" to declare, add

global appconfig

before the very first line appconfig appears.

Hope I can help you. Feel free to comment any other questions about this post.

分享给朋友:
您可能感兴趣的文章:
随机阅读: