" NameError:如何释放变量' var'在分配之前将其引用在封闭范围内".发生在真实代码中? [英] How can "NameError: free variable 'var' referenced before assignment in enclosing scope" occur in real code?

查看:99
本文介绍了" NameError:如何释放变量' var'在分配之前将其引用在封闭范围内".发生在真实代码中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在 Python聊天室中闲逛时,有人进入并报告了以下异常:

While I was hanging out in the Python chatroom, someone dropped in and reported the following exception:

NameError: free variable 'var' referenced before assignment in enclosing scope

我以前从未见过该错误消息,并且用户仅提供了一个小代码片段,它本身并不会导致错误,所以我开始搜索信息,并且……似乎没有很多.当我搜索时,用户报告他们解决的问题是空白问题",然后离开了房间.

I'd never seen that error message before, and the user provided only a small code fragment that couldn't have caused the error by itself, so off I went googling for information, and ... there doesn't seem to be much. While I was searching, the user reported their problem solved as a "whitespace issue", and then left the room.

经过一番尝试后,我只能用玩具代码重现异常:

After playing around a bit, I've only been able to reproduce the exception with toy code like this:

def multiplier(n):
    def multiply(x):
        return x * n
    del n
    return multiply

哪个给我:

>>> triple = multiplier(3)
>>> triple(5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in multiply
NameError: free variable 'n' referenced before assignment in enclosing scope

一切都很好,但是鉴于上面的示例,我很难弄清楚这种异常是如何在野外发生的

All well and good, but I'm having a hard time working out how this exception could occur in the wild, given that my example above is

  1. 愚蠢
  2. 不太可能偶然发生

...但是显然可以,考虑到我在这个问题开始时提到的报告.

... but obviously it does, given the report I mentioned at the start of this question.

那么-这种 如何在真实代码中出现?

So - how can this specific exception occur in real code?

推荐答案

考虑一个更复杂的函数,其中n取决于某些条件,是否取决于某些条件.您不必del有问题的名称,如果编译器看到一个分配,也将发生这种情况,因此该名称是本地的,但不会采用代码路径,因此也不会分配任何名称.另一个愚蠢的例子:

Think of a more complex function where n is bound depending on some condition, or not. You don't have to del the name in question, it also happens if the compiler sees an assignment, so the name is local, but the code path is not taken and the name gets never assigned anything. Another stupid example:

def f():
    def g(x):
        return x * n
    if False:
        n = 10
    return g

这篇关于&quot; NameError:如何释放变量&amp;#39; var&amp;#39;在分配之前将其引用在封闭范围内".发生在真实代码中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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