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

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)))"))


The last line gives the following error

Traceback (most recent call last):
  File "/something/", line 28, in <module>
  File "/something/", 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:04bruno.loffsetrecipients: + bruno.loff
2021-03-23 17:26:04bruno.loffsetmessageid: <>
2021-03-23 17:26:04bruno.lofflinkissue43605 messages
2021-03-23 17:26:04bruno.loffcreate