[issue37780] A strange bug in eval() not present in Python 3

Raymond Hettinger report at bugs.python.org
Tue Aug 6 23:18:03 EDT 2019


Raymond Hettinger <raymond.hettinger at gmail.com> added the comment:

This isn't a bug.  

In Python 2, True and False are variable names rather than keywords.  That means they can be shadowed:

>>> False = 10
>>> True = 20
>>> [False, True]
[10, 20]

A Counter() is a kind a dictionary that returns zero rather than raising a KeyError.  When you give eval() a Counter as a locals() dict, you're effectively shadowing the False and True variables:

>>> eval('[False, True]', {}, Counter())
[0, 0]

That follows from:

>>> c = Counter()
>>> c['True']
0
>>> c['False']
0

So effectively, your example translates to:

>>> [0, 0, 0].count(0)
3

----------
assignee:  -> rhettinger
nosy: +rhettinger
resolution:  -> not a bug
stage:  -> resolved
status: open -> closed

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


More information about the Python-bugs-list mailing list