python - 编码风格 (PEP8) - 模块级别 "dunders"

标签 python pycharm pep8 pep

“Dunder”的定义(Double underscore):http://www.urbandictionary.com/define.php?term=Dunder


根据 Python 代码中模块级别“dunders”(如 __all____version____author__ 等)的位置,我有一个问题.

我在阅读 PEP8 时遇到了这个问题看到this堆栈溢出问题。

接受的答案是:

__author__ is a global "variable" and should therefore appear below the imports.

但是在 PEP8 部分 Module level dunder names我阅读了以下内容:

Module level "dunders" (i.e. names with two leading and two trailing underscores) such as __all__ , __author__ , __version__ , etc. should be placed after the module docstring but before any import statements except from __future__ imports. Python mandates that future-imports must appear in the module before any other code except docstrings.

作者还给出了一个代码示例:

"""This is the example module.

This module does stuff.
"""

from __future__ import barry_as_FLUFL

__all__ = ['a', 'b', 'c']
__version__ = '0.1'
__author__ = 'Cardinal Biggles'

import os
import sys

但是当我将上述内容放入 PyCharm 时,我看到了这个警告(另见屏幕截图):

PEP8: module level import not at top of file

PyCharm ignoring PEP8?

问题:用双下划线存储这些变量的正确方法/位置是什么?

最佳答案

PEP 8 最近更新,将位置放在导入之前。见 revision cf8e888b9555 ,于 2016 年 6 月 7 日提交:

Relax __all__ location.

Put all module level dunders together in the same location, and remove the redundant version bookkeeping information.

Closes #27187. Patch by Ian Lee.

文本是 further updated the next day解决 from __future__ import ... 警告。

补丁链接到 issue #27187 ,它又引用了 this pycodestyle issue ,在哪里发现 PEP 8 尚不清楚。

在此更改之前,由于没有关于模块级 dunder 全局变量的明确指南,因此 PyCharm 和其他答案在当时是正确的。我不确定 PyCharm 如何实现他们的 PEP 8 检查;如果他们使用 pycodestyle project (事实上​​的 Python 样式检查器),那么我确信它会自动修复。否则,也许可以向他们提交错误以查看此问题。

关于python - 编码风格 (PEP8) - 模块级别 "dunders",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39044343/

相关文章:

python - 在 map 中查找成对的附近平行街道的高效算法

python - xlwings 写入特定工作表上的范围

python - 我需要能够通过 USB 运行 pycharm + 模块

indexing - 为什么 PyCharm 对项目根目录之外的目录进行索引?

python - 如何设置 pep8 linter 接受 2 个空格缩进?

python - 是否可以验证youtube/vimeo视频嵌入

python - 递增地增加列表中的非零元素

python - 网站.py : AttributeError: 'module' object has no attribute 'ModuleType' upon running any python file in PyCharm

python - PEP8 和 PyQt,如何协调函数大小写?

python - 如何处理 Python 中的长行代码和命令