List comprehensions leak their loop variable in Py

2019-05-18 03:42发布

问题:

I just learnt from Why do list comprehensions write to the loop variable, but generators don't? that List comprehensions also "leak" their loop variable into the surrounding scope.

Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
>>> x = 'before'
>>> a = [x for x in (1, 2, 3)]
>>> x
3

This bug is fixed in Python3.

Python 3.4.3 (default, Oct 14 2015, 20:28:29) 
>>> x = 'before'
>>> a = [x for x in (1, 2, 3)]
>>> x
'before'

What is the best way to make Python2 be compatible with Python3 at this point?

回答1:

The best way is usually to just not reuse variable names like that, but if you want something that gets the Python 3 behavior in both 2 and 3:

list(x for x in (1, 2, 3))


回答2:

@mgilson's comment is probably the truth, but if you want to write code that works in both python2 and python3, you could wrap a generator function in a list function, Example:

Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
>>> x = 'before'
>>> a = list(x for x in (1, 2, 3))
>>> x
'before'