我正在尝试将值存储在模块级变量中,以便以后检索。
使用GET方法调用此函数时会抛出此错误:local variable 'ICS_CACHE' referenced before assignment
我在这里做错了什么?
ICS_CACHE = None
def ical_feed(request):
if request.method == "POST":
response = HttpResponse(request.POST['file_contents'], content_type='text/calendar')
response['Content-Disposition'] = 'attachment; filename=%s' % request.POST['file_name']
ICS_CACHE = response
return response
elif request.method == "GET":
return ICS_CACHE
raise Http404
我构建了一个基本的例子来查看函数是否可以读取模块常量并且它的工作正常:
x = 5
def f():
print x
f()
---> "5"
答案 0 :(得分:1)
添加
global ISC_CACHE
作为你的功能的第一行。你在函数体内分配它,所以python假定它是一个局部变量。但是,作为局部变量,如果不先分配它,就无法返回它。
全局语句允许解析器知道变量来自函数作用域之外,以便您可以返回其值。
在回复您的第二个发布示例时,您所拥有的内容显示了当您不尝试分配全局变量时解析器如何处理全局变量。
这可能会更清楚:
x = 5 # global scope
def f():
print x # This must be global, since it is never assigned in this function
>>> f()
5
def g():
x = 6 # This is a local variable, since we're assigning to it here
print x
>>> g()
6
def h():
print x # Python will parse this as a local variable, since it is assigned to below
x = 7
>>> h()
UnboundLocalError: local variable 'x' referenced before assignment
def i():
global x # Now we're making this a global variable, explicitly
print x
x = 8 # This is the global x, too
>>> x # Print the global x
5
>>> i()
5
>>> x # What is the global x now?
8