错误消息 "python-pylint 'C0103:Invalid constant name"

Error message "python-pylint 'C0103:Invalid constant name"

我对这张照片中的错误感到困惑:

我不知道如何修复它们。我的程序是一个 Python-Flask 网络框架。当我使用 Visual Studio 代码调试我的程序时,Pylint 显示这些错误。我知道这个问题无关紧要,但这让我很恼火。我该如何解决?

# -*- coding: utf-8 -*-
import sys
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_moment import Moment
#from flask_wtf import Form
#from wtforms import StringField, SubmitField
#from wtforms.validators import Required
from flask_sqlalchemy import SQLAlchemy

reload(sys)
sys.setdefaultencoding('utf-8')

app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost:3306/test?'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

bootstrap = Bootstrap(app)
moment = Moment(app)
db = SQLAlchemy(app)


if __name__ == '__main__':
    db.create_all()
    app.run()

PEP 8 decrees that names of constants should be in all caps.

因此,将这些变量重命名为全部大写。

提示:如果您 google 'C0103' 它将带您到 Pylint 消息 wiki entry for that message,其中包含详细信息。

正如 Kundor 所解释的那样,PEP 8 指出:

Constants are usually defined on a module level and written in all capital letters with underscores separating words.

关键是 Python 中的“常量”并不真正存在。根据 PEP 8,Pylint 期望模块级变量是“常量”。

话虽如此,您有多种选择:

  • 你不想要这个“常量”的东西,然后将 Pylint 的 const-rgx 正则表达式更改为与例如相同variable-rgx,

  • 您可以使用 # pylint: disable=invalid-name

    停用此文件的这些警告,甚至可以在文件本地停用这些警告
  • 通过将它们包装到函数中来避免模块级变量。

在你的情况下,我会选择第三个选项,通过创建一个 build_app 函数或类似的东西。那将是 return 应用程序(也许还有 'db' 对象,但您有多种选择)。然后你可以添加第二个选项的盐来得到类似的东西:

app = build_app() # pylint: disable=invalid-name

将这些变量重命名为全部大写。

比如

app = Flask(__name__)      => APP = Flask(__name__)
bootstrap = Bootstrap(app) => BOOTSTRAP = Bootstrap(app)

事实上 PEP 8 只考虑模块级别的常量,这可能是许多开发人员使用专用 main() 函数的原因。

所以你可以这样解决你的问题:

def main():
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'hard to guess string'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost:3306/test?'
    app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

    bootstrap = Bootstrap(app)
    moment = Moment(app)
    db = SQLAlchemy(app)
    db.create_all()
    app.run()

if __name__ == '__main__':
    main()

您可以在 Python 脚本的开头使用以下行并执行它:

# pylint: disable=invalid-name

它将禁用静态代码分析器中的所有无效常量约定消息。