Pycharm警告解决: shadows name 'xxxx' from outer scope

在Pycharm中写代码,经常会发现代码下出现波浪线。这是因为Pycharm根据pep8风格进行了代码检查。当违背pep8代码风格时,代码下方就会出现波浪线。

强迫症害死人。为了消除所有警告,保持代码颜值,笔者正在对自己代码风格中不规范的地方进行一一纠正。

“shadows name 'xxxx' from outer scope”是一类常见的警告,当变量所在函数被调用的地方已存在同名变量时会提醒。

举个例子:

Pycharm警告解决: shadows name 'xxxx' from outer scope

这里报“shadows name 'word' from outer scope”让我感到很奇怪。在“if __name__ == '__main__':”内部的代码不是应该和say_hello函数内部的代码处于不同的范围吗?两边分别使用word不应该冲突呀。

上stackoverflow一搜,终于明白了。

“You don't actually have a __main__ function, just some module-scope code that's only executed if __name__ == "__main__". Hence there's no local scope for the "main part"; the for loop takes place (and binds x) at module scope.”——from stackoverflow user Ben 

原来,此main并非main函数。。更佳写法应该是:

Pycharm警告解决: shadows name 'xxxx' from outer scope

你看这不就没有波浪线了吗?

回答里的这个老哥讲得也很好:

“ 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:” —— from stackoverflow user Ned Rockson 

 

贴上stackoverflow的帖子链接供参考:

https://stackoverflow.com/questions/31575659/shadows-name-xyz-from-outer-scope?r=SearchResults