Python中是否有类似Harmony' let关键字的东西?

Is there something in Python that is similar to Harmony's let keyword?

本文关键字:关键字 let 是否 Harmony Python      更新时间:2023-09-26

在Harmony中,有一个let关键字允许声明范围为最近块的变量。例如

function foo() {
    if (true){
        let a = 100;
    }
    return a
}

将导致错误,因为a只在if块中定义。

我知道我可以使用del来实现同样的事情,但这是手动而不是自动的,如let关键字

Python为每个类、模块、函数或生成器表达式创建作用域。在代码块中没有作用域。您可以使用嵌套函数来实现预期的目标,例如:

def outside():
    def inside():
        var=5
    print var

在外部调用将导致:

outside()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 5, in outside
NameError: global name 'var' is not defined