Scope of variables declared in main function?

时间:2016-12-09 12:41:06

标签: python variables scope

Simple question about variable scope: Why is it that variables declared in the main function are accessible from external functions? I.e. Why does the following print "yes"?

def run():
    print var

if __name__ == '__main__':
    var = 'yes'
    run()

And is there a way to "turn this off"? In terms of writing good code, it doesn't help to be able to overlook passing variables into functions as arguments, and still have your code run.

2 个答案:

答案 0 :(得分:3)

If-statements don't create new scope in Python. There's no way to "turn this off"; it's a core part of how the language works.

You can use a main function to wrap it in a new scope (this is usually what you want to do; avoid cluttering the namespace) and call it from your main-guard as so:

def run():
    print var

def main():
    var = 'yes'
    run()

if __name__ == '__main__':
    main()

答案 1 :(得分:1)

仅是为了解决将来读者的困惑,让我在这里解释一下幕后发生的事情。在OP的代码中:

def run():
    print var

if __name__ == '__main__':
    var = 'yes'
    run()

var在文件的顶层声明,因此var自动成为全局变量。*然后run()将注意到var存在于全局变量中范围,它只会打印出来。

此行为通常是不希望的*,因此解决方案是避免使var为全局变量。为此,我们需要在函数或类内部声明var。一个例子:

def run():
    print var  # this line will fail, which is what we want

def main():
    var = 'yes'
    run()

if __name__ == '__main__':
    main()

由于var在函数内部声明,因此在这种情况下main()var仅存在于main()的本地范围内。 run()会注意到var在其自己的本地范围内或全局范围内都不存在,并且会失败。

**在Python中,在顶层声明的任何变量(意味着它没有在函数或类中声明,而只是在公开范围内声明)自动被视为全局变量。全局变量可以从任何地方访问。这通常是不希望的。这就是为什么优秀的程序员通常会避免编写顶级代码,而只是将其所有代码放入main()函数或其他函数/类中的原因。

* See why here。或者只是谷歌“ Python为什么全局变量是不可取的”。

相关问题