Python 全局变量、局部变量和 UnboundLocalError [英] Python globals, locals, and UnboundLocalError

查看:39
本文介绍了Python 全局变量、局部变量和 UnboundLocalError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了这个UnboundLocalError的案例,看起来很奇怪:

I ran across this case of UnboundLocalError recently, which seems strange:

import pprint

def main():
    if 'pprint' in globals(): print 'pprint is in globals()'
    pprint.pprint('Spam')
    from pprint import pprint
    pprint('Eggs')

if __name__ == '__main__': main()

产生:

pprint is in globals()
Traceback (most recent call last):
  File "weird.py", line 9, in <module>
    if __name__ == '__main__': main()
  File "weird.py", line 5, in main
    pprint.pprint('Spam')
UnboundLocalError: local variable 'pprint' referenced before assignment

pprint 明确绑定在 globals 中,在下面的语句中将绑定在 locals 中.有人可以解释一下为什么不高兴将 pprint 解析为 globals 中的绑定吗?

pprint is clearly bound in globals, and is going to be bound in locals in the following statement. Can someone offer an explanation of why it isn't happy resolving pprint to the binding in globals here?

多亏了很好的回答,我可以用相关术语来澄清我的问题:

Thanks to the good responses I can clarify my question with relevant terminology:

在编译时标识符 pprint 被标记为框架的本地标识符.执行模型在本地标识符绑定的框架内哪里没有区别吗?是否可以说引用全局绑定直到这个字节码指令,此时它已经被重新绑定到本地绑定",或者执行模型没有考虑到这一点?

At compile time the identifier pprint is marked as local to the frame. Does the execution model have no distinction where within the frame the local identifier is bound? Can it say, "refer to the global binding up until this bytecode instruction, at which point it has been rebound to a local binding," or does the execution model not account for this?

推荐答案

看起来 Python 看到了 from pprint import pprint 行并将 pprint 标记为 pprint 的本地名称code>main() 在执行任何代码之前.由于 Python 认为 pprint 应该是一个局部变量,在使用 from..import 语句分配"它之前使用 pprint.pprint() 引用它,它会抛出该错误.

Looks like Python sees the from pprint import pprint line and marks pprint as a name local to main() before executing any code. Since Python thinks pprint ought to be a local variable, referencing it with pprint.pprint() before "assigning" it with the from..import statement, it throws that error.

这是我所能理解的.

当然,道德是始终将那些 import 语句放在作用域的顶部.

The moral, of course, is to always put those import statements at the top of the scope.

这篇关于Python 全局变量、局部变量和 UnboundLocalError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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