0

This is python:

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

a = a()
print a

it works fine. the output is:

test

now let's try this via WSGI:

def a():
    return 'test'


def application(environ, start_response):

    a = a()

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

the error is:

UnboundLocalError: local variable 'a' referenced before assignment

the only way to fix this error is to rename the variable "a" to something else such as..

 a1 = a()

now there is no longer and error in WSGI.

but why is this ?

1 Answers1

0

In the first example

def a():
    a = 'test' # define a local variable a
    return a # return the local variable a

Both references to a inside the function are the same local variable, that you assign then return.

In the second example:

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

You have references to a a local variable, and a the nonlocal function name mixed together in the same block of code. That's what it doesn't like. It's thinking that if you are talking about the nonlocal a then you would need to put global a at the top of your method. If you are talking about a local variable a then you can't call a() because it doesn't know what that means.

I suggest you probably don't want to reuse your identifiers quite so freely.

khelwood
  • 55,782
  • 14
  • 81
  • 108