0

I am creating new variables by applying lambda functions inside of map() using Python 3.4.

The input sequence to map is a list of dicts. The lambda functions are to be defined in a separate config file. To minimize typing, I wanted to use eval() inside the lambda, like so:

dat = [{'a':1, 'b':2}, {'a':2,'b':1}]
a_transformation = 'a > 1'
temp = map(lambda x: eval(a_transformation,x), dat)

The result is as expected, but it appears each item in the input sequence is changed to the output of global()....

I can do something similar with Pandas without issues:

import pandas
dat = [{'a':1, 'b':2}, {'a':2,'b':1}]
dat_pandas = pandas.DataFrame(a)
a_transformation = 'a > 1'
temp = dat_pandas.eval(a_transformation, engine='python')

But I'd prefer to not have to use Pandas.

Any ideas?

Thanks!

TaylerJones
  • 242
  • 2
  • 15
  • Have you cared to read `eval`'s [documentation](https://docs.python.org/3.4/library/functions.html#eval) at all? "If the globals dictionary is present and lacks `‘__builtins__’`, the **current globals are copied into globals before expression is parsed**. This means that expression normally has full access to the standard builtins module and restricted environments are propagated." – Ashwini Chaudhary Jun 02 '15 at 20:33
  • [Note that the documentation is wrong; it just copies the value of `__builtins__`, not the whole `globals()` dict.](http://bugs.python.org/issue22057) – user2357112 Jun 02 '15 at 20:39
  • Thanks @AshwiniChaudhary , I did not see that in the docs while searching. I am a little confused though - is there a way to avoid what is happening? I mean, I am able to preserve the input if I pass eval copy(dat) instead of just dat, but I am not sure if that is the most efficient way to do what I want (dat is much bigger in practice so I'd like to avoid copying it). Thanks! – TaylerJones Jun 02 '15 at 22:28
  • Nevermind- looks like the way to avoid that is here: http://stackoverflow.com/questions/13491571/how-does-the-eval-function-change-the-dict . I am going to mark this as a duplicate. – TaylerJones Jun 02 '15 at 22:34

0 Answers0