List comprehensions leak their loop variable in Python2: how making it be compatible with Python3

南笙酒味 提交于 2019-12-22 10:30:05

问题


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'


来源:https://stackoverflow.com/questions/37887289/list-comprehensions-leak-their-loop-variable-in-python2-how-making-it-be-compat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!