Python重定义外部变量
python可以任意的重定义外部变量, 这个是bug的根源
样例代码
import os
def prin():
print(os)
def test():
os = "local" # 此处应该出现警告
print(os)
解决方案:
方案 | 结果 |
---|---|
pylance | 没用 |
flake8 | 没用 |
mypy | 没用 |
pylint | OK |
pylint test.py
************* Module code.test
test.py:1:0: C0114: Missing module docstring (missing-module-docstring)
test.py:4:0: C0116: Missing function or method docstring (missing-function-docstring)
test.py:8:0: C0116: Missing function or method docstring (missing-function-docstring)
test.py:9:4: W0621: Redefining name 'os' from outer scope (line 1) (redefined-outer-name)
-----------------------------------
Your code has been rated at 3.33/10
修正文档描述之后的代码
"""Module description."""
import os # 导入变量
def prin():
"""Module description."""
print(os)
def test():
"""Module description."""
os = "local" # 此处会出现黄色波浪线警告
print(os)
此时只剩下一个错误:
pylint test.py
************* Module code.test
test.py:12:4: W0621: Redefining name 'os' from outer scope (line 2) (redefined-outer-name)
------------------------------------------------------------------
Your code has been rated at 8.33/10 (previous run: 8.33/10, +0.00)
配置
# 终端里一键生成一份官方模板
pylint --generate-rcfile > .pylintrc
编辑这个.pylintrc
[MESSAGES CONTROL]
disable=
C0114, # missing-module-docstring
C0116, # missing-function-docstring
C2401, # non-ascii-name ← 这就是你不想要的
R0903, # too-few-public-methods
# …… 想关什么就继续往下加
C, # 所有惯例/格式类
R, # 所有重构建议
W0611, # unused-import(如果你连这也不在乎)
一个重大的结论: setting在这件事上本来就是没用的. pylint只认pylintrc配置文件, 必须在有配置文件的基础上, setting才有用, 即便如此, 也是以配置文件为准.
pylint为啥会对pyside误报: No name ‘QPainterPath’ in module ‘PySide6.QtGui’ Pylint(E0611:no-name-in-module)
方式 | 操作 |
---|---|
快速 (仅当前项目) |
在 .pylintrc 里加一行:extension-pkg-whitelist=PySide6 |
全局 (VS Code 用户) |
settings.json :"python.linting.pylintArgs": ["--extension-pkg-whitelist=PySide6"] |
另外, setting中的键也有修改
"python.linting.pylintEnabled": true, //这个没用了
"python.linting.pylintArgs": [ //这个也没用了
"--disable=C0114,C0116,C2401"
],
"pylint.args": [ //这个才是有用的
"--disable=C0114,C0116,C2401"
],
这个世界清净了, 并且有个更重大的结论:
setting中, vscode说没用的配置, 就是没用的配置.