tags:

views:

55

answers:

1

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?

+2  A: 

you can...

if you did it like this:

#!/usr/bin/env python2.4
'''Simple test of Python scoping rules'''

def enclosing():
    myvariable = 'ooh this worked'

    def myfunction():
         print 'Hope this works: ' + myvariable

    myfunction()

if __name__ == '__main__':
    enclosing()

...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)

Terence Honles
(and if you want to *share* a variable you could add the "global" keyword to both functions so that they share a global variable, but I would **strongly** advise against doing anything like that unless absolutely necessary)
Terence Honles
(i.e. "global myvariable" to the beginning of both functions)
Terence Honles
Thanks Terence. It seems I'd incorrectly assumed that calling functions were considered to be 'enclosing', but the term specifically means the parent of a nested function.
nailer
no worries ;) ...just happened to be flipping to SO, so I figured I'd help
Terence Honles