Python 中 List Comprehensions 的陷阱?

使用 Python 版本: 2.6.6

对于 List Comprehensions 中涉及到的变量,将会修改上下文相同的变量 ::

>>> user_name = "zhangkc"
>>> users = [user_name for user_name in ["zhangkc", "lixc", "caoxj"]]
>>> user_name
'caoxj'

update on 2011,04,21

其实在遇到这个问题的时候的两天后就看到有位外国技术人员在 PyCon 上的相关发布:

PyCon: Cooking with Python 3

其中写道:

If you write "[x * x for x in nums]; print x", x won't be in scope. This is a bit surprising.

在 Python 3.1 和 Python 3.2 解释器中测试过了,果然在 Python 3 中已去掉了这个“陷阱”。


update on 2012,09,16

嗯,这是 Python 早期的一个设计上的问题。在: From List Comprehensions to Generator Expressions 上有记载,解释了早期之所以这样设计的原因:

This was an artifact of the original implementation of list comprehensions; it was one of Python's "dirty little secrets" for years. It started out as an intentional compromise to make list comprehensions blindingly fast, and while it was not a common pitfall for beginners, it definitely stung people occasionally.

Comments

Comment is disabled by administrator.