[New-bugs-announce] [issue43605] Issue of scopes unclear in documentation, or wrongly implemented

Bruno Loff report at bugs.python.org
Tue Mar 23 13:26:04 EDT 2021


New submission from Bruno Loff <bruno.loff at gmail.com>:

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.

----------
messages: 389397
nosy: bruno.loff
priority: normal
severity: normal
status: open
title: Issue of scopes unclear in documentation, or wrongly implemented
type: behavior
versions: Python 3.9

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue43605>
_______________________________________


More information about the New-bugs-announce mailing list