i trying grasp nuances of python namespaces. why eval() on list comp fail when enclosed func passed function containing eval? of these run2x versions work except last 1 run2g.
def sub2(var2): var2 += 1 return var2 def run2c(): # works retrieving sub2 globals print('comp', eval('[sub2(n) n in (1,2,3)]')) def run2h(func): # partial fix cannot access globals in eval() print('arg comp', eval('[func(n) n in (1,2,3)]', locals())) def run2h(func): # fails again on func print('arg comp', eval('[func(n) n in (1,2,3)]', globals(), locals())) def run2g(func): # fails use func in locals print('arg comp', eval('[func(n) n in (1,2,3)]')) # nameerror: name 'func' not defined def run2a(): print('base', eval('sub2(1)')) def run2b(): print('map', list(eval('map(sub2, (1,2,3))'))) def run2c_(): print('comp', eval('[sub2(n) n in (1,2,3)]')) def run2d(func): print('arg', eval('func(1)')) def run2e(func): print('arg map', list(eval('map(func, (1,2,3))'))) def run2f(func): print('arg plain', [func(n) n in (1,2,3)]) def run2g_(func): print('arg comp', eval('[func(n) n in (1,2,3)]')) # nameerror: name 'func' not defined if __name__ == "__main__": run2a() run2b() run2c() run2d(sub2) run2e(sub2) run2f(sub2) run2g(sub2)
python 3.6
Comments
Post a Comment