Pekka Klärck <pekka.kla...@gmail.com> added the comment:

More ways to be bitten by this strange behavior:

    >>> d = {'a': 1, 'b': 2}
    >>> eval('[x[k] for k in x]', {}, {'x': d})
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<string>", line 1, in <module>
      File "<string>", line 1, in <listcomp>
    NameError: name 'x' is not defined
    >>> 
    >>> def f():
    ...     x = {'a': 1, 'b': 2}
    ...     return eval('[x[k] for k in x]')
    ... 
    >>> f()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 3, in f
      File "<string>", line 1, in <module>
      File "<string>", line 1, in <listcomp>
    NameError: name 'x' is not defined



In both of the above cases changing

    eval('[x[k] for k in x]')

to

    eval('[v for v in x.values()]')

avoids the problem. There are no problems when using

    [x[k] for k in x]

without `eval()` either. I'd prefer this to be changed, but there should at 
least be a note in the documentation of `eval()` about this.

----------
nosy: +pekka.klarck

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue36300>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to