Python的全局,当地人和UnboundLocalError [英] Python globals, locals, and UnboundLocalError

查看:287
本文介绍了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 显然是必然全局,并打算在来约束当地人在下面的语句。有人可以提供它为什么不开心解析解释 pprint 全局绑定在这里?

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 标记为本地的框架。是否执行模型没有区别的其中的框架内的本地标识符必然?它可以说,指的是全球性的结合,直到这个字节code指令,此时它已经反弹到本地绑定,还是执行模型没有考虑到这一点?

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看到的从pprint进口pprint 行和标记 pprint 作为名称本地的main()的执行任何code。因为Python认为pprint应该是一个局部变量,用 pprint.pprint() from..import <引用它的分配之前, / code>语句,它抛出这个错误。

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.

这是多大意义,因为我可以让这一点。

That's as much sense as I can make of that.

道德,当然是要始终把那些导入在报表范围的顶端。

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

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

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