名为same as function的变量通过Python正常工作,但不在WSGI脚本中

名为same as function的变量通过Python正常工作,但不在WSGI脚本中,python,python-2.7,mod-wsgi,wsgi,Python,Python 2.7,Mod Wsgi,Wsgi,这是python: #!/usr/bin/python def a(): a = 'test' return a a = a() print a 它很好用。输出为: test 现在,让我们通过WSGI尝试一下: def a(): return 'test' def application(environ, start_response): a = a() start_response('200 OK', [('Content-

这是python:

#!/usr/bin/python
def a():
        a = 'test'
        return a

a = a()
print a
它很好用。输出为:

test
现在,让我们通过WSGI尝试一下:

def a():
    return 'test'


def application(environ, start_response):

    a = a()

    start_response('200 OK', [('Content-Type', 'text/html')])
    yield a
错误是:

UnboundLocalError: local variable 'a' referenced before assignment
修复此错误的唯一方法是将变量“a”重命名为其他变量,如

 a1 = a()
现在WSGI中不再存在错误和错误

但这是为什么呢?

在第一个例子中

def a():
    a = 'test' # define a local variable a
    return a # return the local variable a
函数中对
a
的两个引用都是相同的局部变量,您可以指定该局部变量,然后返回

在第二个例子中:

def application(environ, start_response):
    a = a() # assign something called a to the result of calling itself?
    start_response('200 OK', [('Content-Type', 'text/html')])
    yield a
a
局部变量和
a
非局部函数名的引用混合在同一代码块中。这就是它不喜欢的。它的想法是,如果你谈论的是非局部
a
,那么你需要将
全局a
放在方法的顶部。如果您谈论的是局部变量
a
,那么您不能调用
a()
,因为它不知道这意味着什么


我建议您可能不想如此自由地重用您的标识符。

您有没有看过关于UnboundLocalError的其他无数问题?