如何格式化 flake8 的 Django 设置文件

How to format Django setting file for flake8

我有点沉迷于使用 flake8 格式化我的 python 代码。但是,我在 Django 的设置文件中找不到解决 E501 (line too long x > 79 characters) 的好方法。

首先是这样的(4xE501):

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

然后我想到了这个:

AUTH_PASSWORD_VALIDATORS = [{
    'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    }, {
    'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    }, {
    'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    }, {
    'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

但是 'NAME':django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 还是太长了。有没有办法格式化这个或者我应该忽略这个?

如果除了代码的实际外观之外,您不希望收到此警告,那么您可以通过添加 \ 来打破一行 python 代码(不破坏它的连续性)断点处的字符:

示例:

# 1
from some_module import some_method, some_other_method, \
                        a_third_method

# 2
s = "A really very long string, which exist to mesh with your pep8" \
    " warning free obsession. Well, not anymore!!!"    

注意: 当您要拆分的行在 {}, [] or () 内时,\ 字符会引发错误,因此您可以简单地执行以下操作:

AUTH_PASSWORD_VALIDATORS = [{
    'NAME': 'django.contrib.auth.password_validation.'
            'UserAttributeSimilarityValidator'
    }, ...

考虑到...

,这并没有那么丑

如果您不想要警告并且喜欢您的代码,那么您可以添加:

# nopep8 

在您希望免除 pep8 分析的每一行的末尾。

作为替代方案(以下重写通过 PEP8):

[{"NAME": f"django.contrib.auth.password_validation.{name}"}
 for name in [
    "UserAttributeSimilarityValidator",
    "MinimumLengthValidator",
    "CommonPasswordValidator",
    "NumericPasswordValidator"]]

在 python 2 中,您可以使用 {}".format(name) 而不是 f""

正在查看 Coding style | Django docs 并发现:

An exception to PEP 8 is our rules on line lengths. Don’t limit lines of code to 79 characters if it means the code looks significantly uglier or is harder to read. We allow up to 119 characters as this is the width of GitHub code review.

甚至 Django 的人也避免使用它(他们也更喜欢 flake8 来进行 PEP8 检查)。所以,如果你制作一个 .flake8setup.cfg 文件并输入:

会更好
[flake8]
max-line-length = 119

如果您使用的是 VS 代码....

1) 在您的项目中创建文件夹 (.vscode)。

2) 在文件夹 (.vscode) 中创建 settings.json 文件并粘贴此代码

{
    "team.showWelcomeMessage": false,
    "editor.formatOnSave": true,
    "python.linting.pycodestyleEnabled": false,
    "python.linting.pylintPath": "C:Users/User/AppData/Roaming/Python/Python37/site-packages/pylint",
    "python.linting.pylintArgs": [
        "--load-plugins",
        "pylint_django"
    ],
    "python.linting.pylintEnabled": false,
    "python.linting.enabled": true
}

where "python.linting.pycodestyleEnabled": false, (do FALSE)