在外部范围中定义的阴影名称有多糟糕? [英] How bad is shadowing names defined in outer scopes?

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

问题描述

我刚刚切换到Pycharm,我很高兴所有的警告和提示,它提供我改进我的代码。除了这个我不明白的:



这个检查检测外部范围中定义的阴影名称。



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



以下是一个示例,其中Pycharm向我发出警告消息:

  data = [4,5,6] 

def print_data(data):#< - Warning:Shadows'data'from outer scope
打印数据

print_data(数据)

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



还要记住,在Python中,一切都是一个对象(包括模块,类和函数),所以对于函数,模块或类没有明确的命名空间。另一种情况是,在模块的顶部导入函数 foo ,并在函数体中的某处使用它。然后在你的函数中添加一个新的参数,并命名为 - bad luck - foo



最后,内置函数和类型也存在于同一个命名空间中,并且可以使用相同的方式。



<如果你有短的功能,良好的命名和一个体面的单元测试覆盖率,但是好,有时你必须维护不完美的代码,并警告,这样的可能的问题可能有帮助,这不是一个问题。


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?

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)

解决方案

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

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 unittest coverage, but well, sometimes you have to maintain less than perfect code and being warned about such possible issues might help.

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

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