Colonel Beauvel
Colonel Beauvel

Reputation: 31161

Eval scope in a function

I have the following scripts creating a dictionary from a list of strings:

def dummy(a, b):
    c = a+1
    lst =["a","b","c"]
    return dict((k, eval(k)) for k in lst)

if __name__ == "__main__":
     dummy(0.01, "2015-01-29")

When I run it in terminal, I have the follwoing error:

NameError: name 'a' is not defined

It seems that the variable a is not found in the scope of function dummy when eval acts...but I do not see why ...

Upvotes: 0

Views: 54

Answers (1)

levant pied
levant pied

Reputation: 4481

Make it a list first:

def dummy(a, b):
    c = a + 1
    lst =["a","b","c"]
    return dict([(k, eval(k)) for k in lst])

if __name__ == "__main__":
     print(dummy(0.01, "2015-01-29"))

The version you have is a generator. See this for more details:

To quote the relevant part:

The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods – this includes generator expressions since they are implemented using a function scope.

Upvotes: 1

Related Questions