0

Why does this not work?

f = lambda A, B:[eval(i) for i in 'AB']

In Python 3, the following error is returned:

Traceback (most recent call last):
  File "python", line 1, in <module>
  File "python", line 1, in <lambda>
  File "python", line 1, in <listcomp>
  File "<string>", line 1, in <module>
NameError: name 'A' is not defined

when trying f(1, 2). However, surely the function should return [1, 2]...

0WJYxW9FMN
  • 231
  • 1
  • 2
  • 7
  • what is the purpose of such function? what is the benefit of using `eval` in such simple code? – RomanPerekhrest Feb 18 '17 at 08:19
  • @RomanPerekhrest It's actually for code golf. My actual function is a lot more complicated; I simplified it a lot to make this question clearer. Do you know why it doesn't work? – 0WJYxW9FMN Feb 18 '17 at 08:24
  • 'AB' is just a string consisting of the letter 'A' and 'B'. It has nothing to do with the variables A and B passed to your lambda function. Moreover, eval() applied to integers will lead to TypeError. – limes Feb 18 '17 at 08:26
  • @limes Surely eval('A') would return the value of the parameter A... – 0WJYxW9FMN Feb 18 '17 at 08:28
  • @J843136028: yes, but here you define 'AB'. Where is the variable named AB? You cannot just concatenate two variables into one string. – limes Feb 18 '17 at 08:33
  • @limes So would it work if I did ['A', 'B'] instead? – 0WJYxW9FMN Feb 18 '17 at 08:37
  • `f = lambda A, B:[eval(i) for i in ['A','B']]` `f(1,2)` `NameError: name 'A' is not defined`. No. – limes Feb 18 '17 at 08:44
  • @limes I still don't understand why... – 0WJYxW9FMN Feb 18 '17 at 18:46
  • Possible duplicate of [Python: How can I run eval() in the local scope of a function](http://stackoverflow.com/questions/36616739/python-how-can-i-run-eval-in-the-local-scope-of-a-function) – pvg Feb 18 '17 at 19:05
  • Basically, I think what's going on here is the list comp has its own scope - whatever bindings it needs from the enclosing scope are just made when the comp is created and that's it. But you are trying to resolve, with eval, while the scope is running. There is no binding for these function local vars though so it poops out. It's also a perfectly reasonable (if esoteric) question, not sure why everyone is yelling at you. – pvg Feb 18 '17 at 19:10
  • @pvg Thanks for the detailed, helpful explanation. – 0WJYxW9FMN Feb 18 '17 at 19:19

0 Answers0