I know about the LEGB rule. But a simple test of whether a function has read access to variables defined in an enclosing function doesn’t seem to actually work. Ie:
#!/usr/bin/env python2.4
'''Simple test of Python scoping rules'''
def myfunction():
print 'Hope this works: '+myvariable
def enclosing():
myvariable = 'ooh this worked'
myfunction()
if __name__ == '__main__':
enclosing()
Returns:
NameError: global name 'myvariable' is not defined
Am I doing something wrong? Is there more to it than the LEGB resolution order?
you can…
if you did it like this:
…otherwise your function doesn’t know where to look (well it does, but it looks at the global variables, which is why you are getting the error you are getting) (pass it as a parameter if you can’t define the function as a nested function)