Python 我收到错误“重新定义的外部名称”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24999937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
I am getting the error 'redefined-outer-name'
提问by r23712
When running my lint, I am getting the error below:
运行我的 lint 时,我收到以下错误:
Redefining name 'tmp_file' from outer scope (line 38) (redefined-outer-name)
Here is my snippet of code in that line:
这是我在该行中的代码片段:
tmp_file = open('../build/' + me_filename + '.js','w')
采纳答案by rodrigo
That happens because you have a local name identical to a global name. The local name takes precedence, of course, but it hides the global name, makes it inaccesible, and cause confusion to the reader.
发生这种情况是因为您有一个与全局名称相同的本地名称。当然,本地名称优先,但它隐藏了全局名称,使其无法访问,并导致读者混淆。
Solution
解决方案
Change the local name. Or maybe the global name, whatever makes more sense. But note that the global name may be part of the public module interface. The local name should be local and thus safe to change.
更改本地名称。或者也许是全局名称,任何更有意义的东西。但请注意,全局名称可能是公共模块接口的一部分。本地名称应该是本地的,因此可以安全地更改。
Unless... your intention is for these names to be the same. Then you will need to declare the name as global
in the local scope:
除非……您的目的是使这些名称相同。然后您需要global
在本地范围内声明名称:
tmp_file = None
def do_something():
global tmp_file # <---- here!
tmp_file = open(...)
Without the global
declaration, the local tmp_file
will be unrelated to the global one. Hence the warning.
如果没有global
声明,本地tmp_file
将与全局无关。因此警告。
回答by serv-inc
Open with with
打开用 with
Apart from @Rodrigo's correct answerabout scopes: if your tmp_file
is just that, a temporary file, you can use
除了@Rodrigo关于范围的正确答案:如果你tmp_file
只是一个临时文件,你可以使用
with open('../build/' + me_filename + '.js','w') as tmp_file:
# do something
in both cases. It clearly defines where your tmp_file
is going to be used.
在这两种情况下。它清楚地定义了您将在哪里tmp_file
使用。
It is the recommended wayof dealing with variables whose scope needs to be clearly bounded.
这是处理范围需要明确界定的变量的推荐方法。
Error description
错误描述
Pylint has a built-in description:
Pylint 有一个内置的描述:
pylint --help-msg=redefined-outer-name
gives
给
:redefined-outer-name (W0621): Redefining name %r from outer scope (line %s)Used when a variable's name hide a name defined in the outer scope. This message belongs to the variables checker.
:redefined-outer-name (W0621):从外部作用域(行 %s)重新定义名称 %r当变量的名称隐藏在外部作用域中定义的名称时使用。此消息属于变量检查器。
回答by skipper21
You get this error if you have defined the same variable in multiple places like outside the def and inside the def.
如果您在 def 外部和 def 内部等多个地方定义了相同的变量,则会出现此错误。
If you are using the single variable define it as global variable_name
and use global keyword all the places. Else please rename the other variables.
如果您使用的是单个变量,请将其定义为global variable_name
并在所有位置使用 global 关键字。否则请重命名其他变量。