在外部范围中定义的阴影名称有什么问题?

What is the problem with shadowing names defined in outer scopes?(在外部范围中定义的阴影名称有什么问题?)

本文介绍了在外部范围中定义的阴影名称有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚切换到 PyCharm,我对它为我改进代码提供的所有警告和提示感到非常高兴.除了这个我不明白的:

I just switched to PyCharm and I am very happy about all the warnings and hints it provides me to improve my code. Except for this one which I don't understand:

此检查检测在外部范围中定义的阴影名称.

This inspection detects shadowing names defined in outer scopes.

我知道从外部范围访问变量是不好的做法,但是隐藏外部范围有什么问题?

I know it is bad practice to access variable from the outer scope, but what is the problem with shadowing the outer scope?

这是一个例子,PyCharm 给了我警告信息:

Here is one example, where PyCharm gives me the warning message:

data = [4, 5, 6]

def print_data(data): # <-- Warning: "Shadows 'data' from outer scope
    print data

print_data(data)

推荐答案

上面的代码段没有什么大不了的,但是想象一个有更多参数和更多代码行的函数.然后你决定将你的 data 参数重命名为 yadda,但是错过了它在函数体中使用的地方之一......现在 data指的是全局,并且您开始出现奇怪的行为 - 如果您没有全局名称 data,则会出现更明显的 NameError.

There isn't any big deal in your above snippet, but imagine a function with a few more arguments and quite a few more lines of code. Then you decide to rename your data argument as yadda, but miss one of the places it is used in the function's body... Now data refers to the global, and you start having weird behaviour - where you would have a much more obvious NameError if you didn't have a global name data.

还要记住,在 Python 中,一切都是对象(包括模块、类和函数),因此函数、模块或类没有不同的命名空间.另一种情况是您在模块顶部导入函数 foo,并在函数体的某处使用它.然后你向你的函数添加一个新参数并命名它 - 运气不好 - foo.

Also remember that in Python everything is an object (including modules, classes and functions), so there's no distinct namespaces for functions, modules or classes. Another scenario is that you import function foo at the top of your module, and use it somewhere in your function body. Then you add a new argument to your function and named it - bad luck - foo.

最后,内置函数和类型也存在于同一个命名空间中,并且可以以同样的方式被隐藏.

Finally, built-in functions and types also live in the same namespace and can be shadowed the same way.

如果您有简短的函数、良好的命名和良好的单元测试覆盖率,这都不是什么大问题,但是,有时您必须维护不完美的代码,并且被警告此类可能的问题可能会有所帮助.

None of this is much of a problem if you have short functions, good naming and a decent unit test coverage, but well, sometimes you have to maintain less than perfect code and being warned about such possible issues might help.

这篇关于在外部范围中定义的阴影名称有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在外部范围中定义的阴影名称有什么问题?

基础教程推荐