将版本嵌入 Python 包的标准方法?

2022-01-13 00:00:00 python string package

问题描述

是否有一种标准方法可以将版本字符串与 Python 包相关联,以便我可以执行以下操作?

Is there a standard way to associate version string with a Python package in such way that I could do the following?

import foo
print(foo.version)

我想有一些方法可以在没有任何额外硬编码的情况下检索该数据,因为在 setup.py 中已经指定了次要/主要字符串.我发现的替代解决方案是在我的 foo/__init__.py 中有 import __version__ ,然后由 setup 生成 __version__.py.py.

I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/major strings are specified in setup.py already. Alternative solution that I found was to have import __version__ in my foo/__init__.py and then have __version__.py generated by setup.py.


解决方案

不能直接回答您的问题,但您应该考虑将其命名为 __version__,而不是 version.

Not directly an answer to your question, but you should consider naming it __version__, not version.

这几乎是一个准标准.标准库中的许多模块都使用 __version__,这也用于 很多 第三方模块,所以它是准标准的.

This is almost a quasi-standard. Many modules in the standard library use __version__, and this is also used in lots of 3rd-party modules, so it's the quasi-standard.

通常,__version__ 是一个字符串,但有时它也是一个浮点数或元组.

Usually, __version__ is a string, but sometimes it's also a float or tuple.

如 S.Lott 所述(谢谢!),PEP 8 明确表示:

as mentioned by S.Lott (Thank you!), PEP 8 says it explicitly:

模块级别的dunders"(即具有两个前导和两个尾随的名称下划线),例如 __all____author____version__ 等.应该放在模块文档字符串之后但在任何导入之前除了来自 __future__ 导入的语句.

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.

您还应该确保版本号符合 PEP 440 中描述的格式(PEP 386 本标准的先前版本).

You should also make sure that the version number conforms to the format described in PEP 440 (PEP 386 a previous version of this standard).

相关文章