Python variable assigned by an outside module is accessible for printing but not for assignment in the target module

时光总嘲笑我的痴心妄想 提交于 2019-12-20 04:21:01

问题


I have two files, one is in the webroot, and another is a bootstrap located one folder above the web root (this is CGI programming by the way).

The index file in the web root imports the bootstrap and assigns a variable to it, then calls a a function to initialize the application. Everything up to here works as expected.

Now, in the bootstrap file I can print the variable, but when I try to assign a value to the variable an error is thrown. If you take away the assignment statement no errors are thrown.

I'm really curious about how the scoping works in this situation. I can print the variable, but I can't asign to it. This is on Python 3.

index.py

# Import modules
import sys
import cgitb;

# Enable error reporting
cgitb.enable()
#cgitb.enable(display=0, logdir="/tmp")

# Add the application root to the include path
sys.path.append('path')

# Include the bootstrap
import bootstrap

bootstrap.VAR = 'testVar'

bootstrap.initialize()

bootstrap.py

def initialize():
    print('Content-type: text/html\n\n')
    print(VAR)
    VAR = 'h'
    print(VAR)

Thanks.

Edit: The error message

UnboundLocalError: local variable 'VAR' referenced before assignment 
      args = ("local variable 'VAR' referenced before assignment",) 
      with_traceback = <built-in method with_traceback of UnboundLocalError object at 0x00C6ACC0>

回答1:


try this:


def initialize():
    global VAR
    print('Content-type: text/html\n\n')
    print(VAR)
    VAR = 'h'
    print(VAR)

Without 'global VAR' python want to use local variable VAR and give you "UnboundLocalError: local variable 'VAR' referenced before assignment"




回答2:


Don't declare it global, pass it instead and return it if you need to have a new value, like this:

def initialize(a):
    print('Content-type: text/html\n\n')
    print a
    return 'h'

----

import bootstrap
b = bootstrap.initialize('testVar')


来源:https://stackoverflow.com/questions/605399/python-variable-assigned-by-an-outside-module-is-accessible-for-printing-but-not

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!