在外部作用域中定义的阴影名称有什么问题? [英] What is the problem with shadowing names defined in outer scopes?

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

问题描述

我刚刚切换到 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.

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

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