TheOne
TheOne

Reputation: 11159

django module-level cache

I am trying to store a value in a module level variable for later retrieval. This function when called with a GET method throws this error: local variable 'ICS_CACHE' referenced before assignment

What am I doing wrong here?

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

I constructed a basic example to see if a function can read module constants and it works just fine:

x = 5

def f():
    print x

f()

---> "5"

Upvotes: 0

Views: 336

Answers (1)

Ian Clelland
Ian Clelland

Reputation: 44152

Add

global ISC_CACHE

as the first line of your function. You are assigning to it inside the function body, so python assumes that it is a local variable. As a local variable, though, you can't return it without assigning to it first.

The global statement lets the parser know that the variable comes from outside of the function scope, so that you can return its value.

In response to your second posted example, what you have shows how the parser deals with global variables when you don't try to assign to them.

This might make it more clear:

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

Upvotes: 1

Related Questions