列表推导中定义的变量是否泄漏到封闭范围内? [英] Do variables defined inside list comprehensions leak into the enclosing scope?

查看:54
本文介绍了列表推导中定义的变量是否泄漏到封闭范围内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到定义此行为的任何地方:

I can't find anywhere that defines this behaviour:

if [x for x in [0, 1, -1] if x > 0]:
    val = x

此代码的安全性如何?如果列表中的任何元素大于0,是否总是将val分配给列表中的最后一个元素?

How safe is this code? Will val always be assigned to the last element in the list if any element in the list is greater than 0?

推荐答案

在Python 2.x中,列表推导中定义的变量泄漏到其封闭范围内,因此,val将始终绑定到绑定到的最后一个值x在列表理解期间(只要理解的结果是非空的,因此是真实的"列表).

In Python 2.x, variables defined inside list comprehensions leak into their enclosing scope, so yes, val will always be bound to the last value bound to x during the list comprehension (as long as the result of the comprehension is a non-empty, and therefore "truthy", list).

但是,在Python 3.x中,情况不再如此:

However, in Python 3.x, this is no longer the case:

>>> x = 'foo'
>>> if [x for x in [0, 1, -1] if x > 0]:
...     val = x
... 
>>> val
'foo'

(几乎没有)在此处中记录该行为:

The behaviour is (just barely) documented here:

在Python 2.3和更高版本中,列表理解将其包含的每个for的控制变量泄漏"到包含作用域中.但是,此行为已被弃用,并且依赖于它在Python 3中将无法正常工作.

In Python 2.3 and later releases, a list comprehension "leaks" the control variables of each for it contains into the containing scope. However, this behavior is deprecated, and relying on it will not work in Python 3.

...,并在此处:

[...] 请注意,列表推导具有不同的语义:对于

[...] note that list comprehensions have different semantics: they are closer to syntactic sugar for a generator expression inside a list() constructor, and in particular the loop control variables are no longer leaked into the surrounding scope.

2.x的行为似乎并不是任何人特别引以为傲的,实际上,Guido van Rossum在

It would appear that the 2.x behaviour wasn't something anyone was particularly proud of, and in fact Guido van Rossum refers to it as 'one of Python's "dirty little secrets"' in a blog post.

这篇关于列表推导中定义的变量是否泄漏到封闭范围内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆