Message389397
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. |
|
Date |
User |
Action |
Args |
2021-03-23 17:26:04 | bruno.loff | set | recipients:
+ bruno.loff |
2021-03-23 17:26:04 | bruno.loff | set | messageid: <1616520364.91.0.0936665126175.issue43605@roundup.psfhosted.org> |
2021-03-23 17:26:04 | bruno.loff | link | issue43605 messages |
2021-03-23 17:26:04 | bruno.loff | create | |
|