問(wèn)題描述
是否有一種標(biāo)準(zhǔn)方法可以將版本字符串與 Python 包相關(guān)聯(lián),以便我可以執(zhí)行以下操作?
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)
我想有一些方法可以在沒(méi)有任何額外硬編碼的情況下檢索該數(shù)據(jù),因?yàn)樵?setup.py
中已經(jīng)指定了次要/主要字符串.我發(fā)現(xiàn)的替代解決方案是在我的 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
.
推薦答案
不能直接回答您的問(wèn)題,但您應(yīng)該考慮將其命名為 __version__
,而不是 version
.
Not directly an answer to your question, but you should consider naming it __version__
, not version
.
這幾乎是一個(gè)準(zhǔn)標(biāo)準(zhǔn).標(biāo)準(zhǔn)庫(kù)中的許多模塊都使用 __version__
,這也用于 很多 第三方模塊,所以它是準(zhǔn)標(biāo)準(zhǔn)的.
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__
是一個(gè)字符串,但有時(shí)它也是一個(gè)浮點(diǎn)數(shù)或元組.
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:
模塊級(jí)別的dunders"(即具有兩個(gè)前導(dǎo)和兩個(gè)尾隨的名稱下劃線),例如 __all__
、__author__
、__version__
等.應(yīng)該放在模塊文檔字符串之后但在任何導(dǎo)入之前除了來(lái)自 __future__
導(dǎo)入的語(yǔ)句.
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.
您還應(yīng)該確保版本號(hào)符合 PEP 440 中描述的格式(PEP 386 本標(biāo)準(zhǔn)的先前版本).
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).
這篇關(guān)于將版本嵌入 Python 包的標(biāo)準(zhǔn)方法?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!