如何在“赋值之前在引用范围”中引用“NameError:free variable'var'发生在实际代码? [英] How can "NameError: free variable 'var' referenced before assignment in enclosing scope" occur in real code?

查看:275
本文介绍了如何在“赋值之前在引用范围”中引用“NameError:free variable'var'发生在实际代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  NameError:在赋值之前引用的自由变量'var'在封闭范围内引用

我从来没有看到这个错误消息,用户只提供了一个小的代码片段,不能导致自己的错误,所以我去谷歌搜索信息,和...似乎没有太多。在我搜索时,用户报告他们的问题解决了作为空白问题,然后离开了房间。



玩了一会儿后,我只有能够用下面的玩具代码重现异常:

 def $ $ b def multiply(x):
return x * n
del n
return multiply

这给了我:

 >> triple = multiplier(3)
>>>> triple(5)
Traceback(最近一次调用):
在< module>中的文件< stdin&
文件< stdin>,第3行,乘以
NameError:在包含范围内的赋值之前引用的自由变量'n'

一切都很好,但我很难知道这种异常如何在野外发生,因为我上面的例子是


  1. 很愚蠢

  2. 不太可能发生意外


b $ b

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



考虑一个更复杂的函数,其中 n <>

/ code>是根据一些条件绑定,还是不绑定。你不需要 del 有问题的名字,如果编译器看到一个赋值,也会发生,所以名称是本地的,但是代码路径不被采取,名称从未分配任何东西。另一个愚蠢的例子:

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


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

Which gives me:

>>> 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. Pretty stupid
  2. Unlikely to happen by accident

... 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?

解决方案

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

这篇关于如何在“赋值之前在引用范围”中引用“NameError:free variable'var'发生在实际代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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