“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
问题:用双下划线存储这些变量的正确方法/位置是什么?
最佳答案
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/