Why can't my function access a variable in an enclosing function?

Posted by nailer on Stack Overflow See other posts from Stack Overflow or by nailer
Published on 2010-06-01T09:22:20Z Indexed on 2010/06/01 9:23 UTC
Read the original article Hit count: 162

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about python

Related posts about scope