python - Creating a dict with dictionary comprehension and eval() gives me NameError -
i trying create dictionary dictionary comprehensions in following way (which part of larger code)
columns = ['zeta', 'lm', 'u_mean'] print('zeta', eval('zeta')) print(locals()) dic = {col: [eval(col)] col in columns} the first print prints expected (the value of variable zeta) , second print confirms zeta in locals dictionary, in dictionary comprehension command python fails error
nameerror: name 'zeta' not defined unfortunately, when trying reproduce error in order post here, found out can't reproduce error, because following commands work in ipython:
zeta,lm,u_mean=1,4,69 columns=['zeta', 'lm', 'u_mean'] print('zeta',eval('zeta')) print(locals()) dic={ col : [eval(col)] col in columns } it commands inside code not work. so, missing something? there test can see what's wrong?
a dictionary comprehension executed in new scope, lot nested function call. cannot expect access locals of parent scope in list comprehension.
i recommend not use locals this. create separate dictionary act namespace , columns in that:
namespace = { 'zeta': value_for_zeta, # ... etc. } then use {col: [namespace[col]] col in columns}.
failing that, can store locals() dictionary in new variable , reference that; either directly, or through passing in namespace eval():
namespace = locals() dic = {col: [eval(col, namespace)] col in columns} or simply:
namespace = locals() dic = {col: [namespace[col]] col in columns} this works because namespace closure; name taken parent scope.
note same limits apply generator expressions, set comprehensions, , in python 3, list comprehensions. python 2 list comprehensions implemented before other types , followed different implementation strategy did not involve new scope, approach did not allow generator expressions work , new approach separate scope found work better.
Comments
Post a Comment