Author bruno.loff
Recipients bruno.loff
Date 2021-03-23.17:26:04
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1616520364.91.0.0936665126175.issue43605@roundup.psfhosted.org>
In-reply-to
Content
Python 3.9.2 seems to be giving me some unexpected difficulty evaluating generators inside evals. Here is the example:

```python
def func(l):
    def get(i):
        return l[i]


    print(sum(get(i) for i in range(len(l)))) # works as expected, prints 10
    print(eval("get(0) + get(1) + get(2) + get(3)")) # works just fine, prints 10

    # if __globals is set to locals(), it still works, prints 10
    print(eval("sum(get(i) for i in range(len(l)))", locals()))

    # This will complain
    print(eval("sum(get(i) for i in range(len(l)))"))

func([1,2,3,4])
```

The last line gives the following error

```
Traceback (most recent call last):
  File "/something/test_eval.py", line 28, in <module>
    func([1,2,3,4])
  File "/something/test_eval.py", line 10, in func
    print(eval("sum(get(i) for i in range(len(l)))"))  # this does not work... bug?
  File "<string>", line 1, in <module>
  File "<string>", line 1, in <genexpr>

NameError: name 'get' is not defined
```

Any kind of generator-based code wont work. The following lines would give the same an error:
```
print(eval("sum(get(i) for i in range(len(l)))"), globals(), locals())
print(eval("[get(i) for i in range(len(l))]"))
print(eval("{i:get(i) for i in range(len(l))}"))
```


Any clue what is happening? The documentation on eval seems to give no insight on why this behavior is as is. This really feels like an issue, at the very least, it's an issue in the documentation.
History
Date User Action Args
2021-03-23 17:26:04bruno.loffsetrecipients: + bruno.loff
2021-03-23 17:26:04bruno.loffsetmessageid: <1616520364.91.0.0936665126175.issue43605@roundup.psfhosted.org>
2021-03-23 17:26:04bruno.lofflinkissue43605 messages
2021-03-23 17:26:04bruno.loffcreate