Python 来自外部范围的阴影名称 xyz

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31575659/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:15:16  来源:igfitidea点击:

Shadows name xyz from outer scope

pythonpython-2.7pycharm

提问by The Wanderer

I am using pycharmand it lists out all the errors/warnings associated with the code. While I understand most of them I am not sure of this one "Shadows name xyz from outer scope". There are a few SO posts regarding this: How bad is shadowing names defined in outer scopes?but then they seem to be accessing a global variable.

我正在使用pycharm,它列出了与代码相关的所有错误/警告。虽然我了解其中的大多数,但我不确定这个“来自外部范围的阴影名称 xyz”。有一些关于此的 SO 帖子:在外部作用域中定义的阴影名称有多糟糕?但随后他们似乎正在访问一个全局变量。

In my case, my __main__function has a few variable names and then it is calling another function sample_funcwhich uses those variable names again (primarily the loop variable names). I am assuming because I am in a different function, the scope for these variables will be local, however the warning seem to suggest otherwise.

在我的例子中,我的__main__函数有几个变量名,然后它调用另一个sample_func再次使用这些变量名的函数(主要是循环变量名)。我假设因为我在不同的函数中,这些变量的作用域将是本地的,但是警告似乎另有暗示。

Any thoughts? For your reference here is some code:

有什么想法吗?这里有一些代码供您参考:

def sample_func():
    for x in range(1, 5):  --> shadows name x from outer scope
        print x

if __name__ == "__main__":
    for x in range(1, 5):
        sample_func()

采纳答案by mehtunguh

The warning is about the potential danger you are introducing by re-using these names at inner scopes. It can cause you to miss a bug. For example, consider this

警告是关于您通过在内部范围内重用这些名称而引入的潜在危险。它可能会导致您错过一个错误。例如,考虑这个

def sample_func(*args):
    smaple = sum(args) # note the misspelling of `sample here`
    print(sample * sample)

if __name__ == "__main__":
    for sample in range(1, 5):
        sample_func()

Because you used the same name, your misspelling inside the function does not cause an error.

因为您使用了相同的名称,所以您在函数内的拼写错误不会导致错误。

When your code is very simple, you will get away with this type of thing with no consequences. But it's good to use these "best practices" in order to avoid mistakes on more complex code.

当您的代码非常简单时,您将摆脱这种类型的事情而不会产生任何后果。但是最好使用这些“最佳实践”以避免在更复杂的代码上出错。

回答by Padraic Cunningham

It is just a warning, as explained in the linked question there are times when it can cause issues but in you case xis local to your function. You are getting the warning because of the xinside your if __name__ == "__main__":being in globals. It won't have any effect on the xin your function so I would not worry about the warning.

这只是一个警告,如链接问题中所述,有时它可能会导致问题,但在您的情况下x是您的函数的本地问题 。您收到警告是因为xif __name__ == "__main__":在全局变量中的内部。它不会对x您的函数产生任何影响,所以我不会担心警告。

回答by Ned Rockson

The code inside of your if branch of your main function is actually in scope when you're inside of sample_func. You can read from the variable x(try it out). This is okay as you don't really care about it so you have a few options to move forward.

当您在 sample_func 中时,您的 main 函数的 if 分支中的代码实际上在范围内。您可以从变量中读取x(尝试一下)。这没关系,因为您并不真正关心它,因此您有一些选择可以继续前进。

1) Disable shadowing warnings in pycharm. Honestly this is the most straightforward and depending on how experienced of a coder you are it probably makes the most sense (if you're relatively new I would not do this though.)

1) 在 pycharm 中禁用阴影警告。老实说,这是最直接的,并且取决于您的编码员的经验,这可能最有意义(如果您相对较新,我不会这样做。)

2) Put your main code into a main function. This is probably the best solution for any production level code. Python is very good at doing things the way you want to do them so you should be careful not to fall into traps. If you are building a module, having lots of logic at the module level can get you into sticky situations. Instead, something like the following could be helpful:

2)把你的主代码放到一个主函数中。这可能是任何生产级代码的最佳解决方案。Python 非常擅长按照你想要的方式做事,所以你应该小心不要落入陷阱。如果您正在构建一个模块,在模块级别拥有大量逻辑会使您陷入困境。相反,以下内容可能会有所帮助:

def main():
    # Note, as of python 2.7 the interpreter became smart enough
    # to realize that x is defined in a loop, so printing x on this
    # line (prior to the for loop executing) will throw an exception!
    # However, if you print x by itself without the for loop it will
    # expose that it's still in scope. See https://gist.github.com/nedrocks/fe42a4c3b5d05f1cb61e18c4dabe1e7a
    for x in range(1, 5):
        sample_func()

if __name__ == '__main__':
    main()

3) Don't use the same variable names that you're using in broader scopes. This is pretty hard to enforce and is kinda the opposite of #1.

3) 不要使用您在更广泛范围内使用的相同变量名称。这很难执行,并且与#1 正好相反。

回答by Mark Smith

I know this is an old thread and this isn't appropriate for the problem the asker was trying to find out about, but I was searching for an answer to why PyCharm was showing me a 'Shadows name from outer scope' message on a complex if/elif statement block...

我知道这是一个旧线程,这不适合提问者试图找出的问题,但我正在寻找一个答案,以解释为什么 PyCharm 向我显示一个复杂的“来自外部范围的阴影名称”消息if/elif 语句块...

It turns out I had capitalised some global variable names at the start of the function but used lower case in my if/elif block much further down in the function.

事实证明,我在函数的开头将一些全局变量名大写,但在函数中更远的 if/elif 块中使用了小写。

School boy error I know, but once I corrected this, the 'Shadows name from outer scope' message in PyCharm disappeared and the variables stopped showing as greyed out...

我知道男生错误,但是一旦我纠正了这个错误,PyCharm 中的“来自外部范围的阴影名称”消息就消失了,变量不再显示为灰色......

So the lesson I learned is that this PyCharm message may be caused by something as simple as a upper/lower case error in a variable name...

所以我学到的教训是,这个 PyCharm 消息可能是由一些简单的事情引起的,比如变量名中的大写/小写错误......

I only realised the problem while I was breaking the function into three functions to see if this would remove the 'Shadows...' error, as I was thinking I had an issue with indentation and this was causing the problem!

我只是在将函数分解为三个函数以查看这是否会消除“阴影...”错误时才意识到这个问题,因为我认为我有缩进问题,这是导致问题的原因!

This may help another newbie who is scratching their head wondering why they are getting this error :-)

这可能会帮助另一个正在挠头想知道为什么他们会收到此错误的新手:-)

回答by David Baucum

I was running into this warning for an argument in a method named year, but no other variable was sharing that name. I then realized that it was because of the line from pyspark.sql.functions import *which was importing a yearvariable. Changing this to only import the functionality we needed go rid of the warning.

我因为名为 的方法中的参数而遇到此警告year,但没有其他变量共享该名称。然后我意识到这是因为from pyspark.sql.functions import *导入year变量的行。将此更改为仅导入我们需要的功能以消除警告。