Alex
Alex

Reputation: 44345

Python Name Error in dict comprehension when called inside a function

I have the following python2 code which gives a NameError:

def myfunc():


   myvar=50
    print myvar
    print eval('myvar')
    a = 'myvar'
    print { a:eval(a) }
    print { a:a for a in ['myvar'] }
    print { a:eval(a) for a in ['myvar'] }

myfunc()

and when I now execute this python code with python2, I get the following output:

50
50
{'myvar': 50}
{'myvar': 'myvar'}
Traceback (most recent call last):
  File "tester.py", line 13, in <module>
    myfunc()
  File "tester.py", line 11, in myfunc
    print { a:eval(a) for a in ['myvar'] }
  File "tester.py", line 11, in <dictcomp>
    print { a:eval(a) for a in ['myvar'] }
  File "<string>", line 1, in <module>
NameError: name 'myvar' is not defined

Remark: This is running on a Mac... When I run the code snippet OUTSIDE of a function it works as expected...

Upvotes: 2

Views: 366

Answers (1)

Martin Stone
Martin Stone

Reputation: 13007

You can work around this by doing...

globs, locs = globals(), locals()
print { a:eval(a, globs, locs) for a in ['myvar'] }

An explanation can be found here: eval fails in list comprehension

Upvotes: 1

Related Questions