2

I have to access free variables in exec in nested method in python(2.6)

def outerF():
    la = 5
    def innerF():
        str1 = "print(la)"
        exec (str1) in globals(),locals()
    innerF()
outerF()

The expected result is 5 but I am getting the following error

NameError: name 'la' is not defined

Vicky Gupta
  • 576
  • 6
  • 13
  • You can't. Not in Python 2, where there is no concept of marking variables you bind to as nonlocal. – Martijn Pieters Jan 02 '19 at 10:28
  • Moreover, `la` is **not a free variable**. Variables are only marked as free when the compiler sees that there is a nested function that uses the name, and there is no such use here at compile time. By the time `exec` is executed it's too late to change this. – Martijn Pieters Jan 02 '19 at 10:33
  • Closure : It is a function object that remembers values in enclosing scopes even if they are not present in memory. To solve this you need to use **nonlocal** keyword You can check use of **nonlocal** and details about **Closure** in following link for more info https://www.learnpython.org/en/Closures – AviatorX Jan 02 '19 at 10:39

3 Answers3

0

for python 2.6

def outerF():
    la={'y': 5} # exec take argu as dict and in 2.6 nonlocal is not working, 
    # have to create dict element and then process it 
    def innerF():

        str1 = "print({})".format(la['y'])
        exec (str1) in globals(),locals()
    innerF()
outerF()
sahasrara62
  • 10,069
  • 3
  • 29
  • 44
0

Use nonlocal to access outer function's variable in nested functions as: Python Global, Local and Nonlocal variables

def outerF():
    la = 5
    def innerF():
        nonlocal la    #it let the la variable to be accessed in inner functions.
        str1 = "print(la)"
        exec (str1) in globals(),locals()
    innerF()
outerF()
khelwood
  • 55,782
  • 14
  • 81
  • 108
ThunderMind
  • 789
  • 5
  • 14
0

Please try using nonlocal statement for your variable. Like this:

def outerF():
    la = 5
    def innerF():
        nonlocal la
        str1 = "print(la)"
        exec (str1) in globals(),locals()
    innerF()
outerF()

More info could be found here: Python Global, Local and Nonlocal variables

ThunderMind
  • 789
  • 5
  • 14
Alexander Lyapin
  • 305
  • 1
  • 14