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

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

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

“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函数。。更佳写法应该是:

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

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

“ 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

  • 59
    点赞
  • 60
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值