Looking for objects in the application area

I am new to programming and will look through some topics about functions and classes. So after reading about functions and closing functions, I tried to simulate finding inheritance in classes with just mini-functions and scoping.

Example:

For code

def f1():
    t=1
    def f2(x):
        return eval(x)
    return f2

      

Why am I getting a name error when executing

f1()('t') #expecting 1 return

But not when defining a word

def f1():
    t=1
    def f2():
         return t
    return f2

      

f()() # 1 is returned here

I could solve this problem by defining t as non-local in area f2, which means that the first code is only seen in local area f2. Why is this happening? `

+3


source to share


1 answer


The problem here is in the context of eval . By default, eval uses locals and globals from the environment in which it is called. If we write:

def f1():
    t = 1

    def f2(x):
        return eval(x)
    return f2

      

then internally f2

, it is t

not included in either global or local, and therefore will be inaccessible to the eval statement. Python will add t

locals for f2

if t

actually used in f2

. Thus, somewhat surprisingly, the following code will execute correctly:

def f1():
    t = 1

    def f2(x):
        print(t)
        return eval(x)
    return f2

      



since it is t

now used in f2

. The best way to ensure this is always to do the following:

def f1():
    t = 1
    eval_globals = globals()
    eval_locals = locals()

    def f2(x):
        return eval(x, eval_globals, eval_locals)
    return f2

      

This overrides the context for eval by providing global and local objects from scope f1

.

Caveat as you mention you are a new programmer: in general, you should avoid the eval statement period unless you have a compelling reason to use them. There are better ways to accomplish what you are doing here without resorting to eval.

+1


source







All Articles