接收到"UnboundLocalError:赋值之前引用的局部变量'e".变量何时初始化 [英] Received "UnboundLocalError: local variable 'e' referenced before assignment" when the variable was initialized

查看:73
本文介绍了接收到"UnboundLocalError:赋值之前引用的局部变量'e".变量何时初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[社区编辑以提供可复制的示例:]

def main():
    e = None
    print(locals())
    while not e:
        try:
            raise Exception
        except Exception as e:
            pass            

main()

产生

~/coding$ python3.3 quiz2.py
{'e': None}
Traceback (most recent call last):
  File "quiz2.py", line 11, in <module>
    main()
  File "quiz2.py", line 5, in main
    while not e:
UnboundLocalError: local variable 'e' referenced before assignment


[已编辑]包含可复制的代码


to include a reproducible code

我正在尝试运行while循环,而我使用的条件是,当变量 e == None 时,循环将继续.相关代码如下:

I am trying to run a while-loop, and the condition I use is that the loop continues when the variable e==None. The relevant code is below:

    print("\nThe current score list contains the following people's scores: ")
    score_list = open("score_list.dat", "rb")
    score_name = []
    e = None
    while not e:
        try:
            score = pickle.load(score_list)
            name = pickle.load(score_list)
            score_name.append([score, name])
        except EOFError as e:
            pass            
    score_list_sorted=sorted(score_list)
    sort_list.close()
    for item in score_list_sorted:
        print("Score: ", item[0], "\t", item[1])

完整的代码在这里: https://www.dropbox.com/s/llj5xwexzfsoppv/stats_quiz_feb24_2013.py

它(运行测验)所需的数据文件在此链接中: https://www.dropbox.com/s/70pbcb80kss2k9e/stats_quiz.dat

The data file it requires (for the quiz to run) is in this link: https://www.dropbox.com/s/70pbcb80kss2k9e/stats_quiz.dat

main()以使用正确的数据文件地址:

main() needs to be edited to use the proper data file address:

以下是我收到的完整错误消息.这很奇怪,因为我在while循环之前初始化了 e .我希望有人可以帮助我解决这个问题.谢谢!

The complete error message I received is below. This is weird because I initialized e right before the while-loop. I hope someone can help me resolve this problem. Thanks!

Traceback (most recent call last):
  File "<pyshell#217>", line 1, in <module>
    main()
  File "/Users/Dropbox/folder/stats_quiz_feb24_2013.py", line 83, in main
    while not e:
UnboundLocalError: local variable 'e' referenced before assignment

推荐答案

好吧,我不知道是什么导致了实际的问题,但是为什么您不只在发生异常时才使用 break ?您的循环变为:

Well, I don't know what's causing the actual problem, but why don't you just use break when an exception occurs? Your loop becomes:

while True:
    try:
        score = pickle.load(score_list)
        name = pickle.load(score_list)
        score_name.append([score, name])
    except EOFError as e:
        break

据我所知,这是实现无例外的运行循环"的惯用方式.

As far as I know, this is the idiomatic way of achieving "run loop while there's no exception"

修改:为什么会发生

似乎在python3中,一旦退出异常处理程序的范围,绑定到异常的变量就会从名称空间中删除.我将代码修改为以下内容:

It would seem that in python3, once you exit the scope of an exception handler, the variable that the exception was bound to is removed from the namespace. I modified the code to the following:

def main():
    e = None
    print(locals())
    while not e:
        try:
            raise Exception
        except Exception as e:
            pass
        print(locals())

main()

输出:

{'e': None}
{}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in main
UnboundLocalError: local variable 'e' referenced before assignment

在python2中不是这种情况.鉴于更改了如何将异常分配给变量的语法,因此更改语义也就不足为奇了.尽管我确实认为这是令人惊讶的"行为(从某种意义上说,这并不是您所期望的).

This is not the case in python2. Given that the syntax was changed for how you assign an exception to a variable, I'm not surprised that the semantics of it were changed as well. Although I do think that this is "surprising" behaviour(in the sense that it is not what you would expect).

无论如何,上面的代码中出现异常时退出循环的正确方法是.如果您想将异常保持在异常处理程序的范围之外,我想您仍然可以执行以下操作:

In any case, the proper way to exit a loop when an exception occurs is in the code above. If you want to keep the exception outside of the exception handler's scope I guess you could still do something like this:

def main():
   e = None
   print(locals())
   while not e:
      try:
         raise Exception
      except Exception as ex:
         e = ex
      print(locals())

main()

哪个会产生以下输出:

{'e': None}
{'e': Exception()}

但是对于您的特定用例,您确实不应该这样做.

But you really shouldn't be doing that for your particular use-case.

这篇关于接收到"UnboundLocalError:赋值之前引用的局部变量'e".变量何时初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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