tags:

views:

367

answers:

2

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>
+3  A: 

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"

Mykola Kharechko
Thanks, your post pointed me in the right direction.Further info can be found here.http://stackoverflow.com/questions/370357/python-variable-scope-question
Douglas Brunner
A: 

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')
ironfroggy
Yes that will get around the scoping issue and I use that method in other situations; but in this situation the index.py file isn't supposed to do any kind of processing, it's only supposed to set a few values. The bootstrap is actually responsible for loading another class which does the processing
Douglas Brunner