简体   繁体   English

python包中的常量

[英]Constants in a python package

I'm writing a python package and am wondering where the best place is to put constants? 我正在写一个python包,我想知道放置常量的最佳位置在哪里?

I know you can create a file called 'constants.py' in the package and then call them with module.constants.const, but shouldn't there be a way to associate the constant with the whole module? 我知道你可以在包中创建一个名为'constants.py'的文件,然后用module.constants.const调用它们,但是不应该有办法将常量与整个模块相关联吗? eg you can call numpy.pi, how would I do something like that? 例如你可以打电话给numpy.pi,我该怎么办呢?

Also, where in the module is the best place to put paths to directories outside of the module where I want to read/write files? 此外,模块中的哪个位置是将路径放到模块外部目录的最佳位置,我想要读/写文件?

Put them where you feel they can most easily be maintained. 把它们放在你认为最容易维护的地方。 Usually that means in the module to which the constants logically belong. 通常,这意味着常量逻辑上属于的模块。

You can always import the constants into the __init__.py file of your package to make it easier for someone to find them. 您始终可以将常量导入到包的__init__.py文件中,以便人们更容易找到它们。 If you did decide on a constants module, I'd add a __all__ sequence to state what values are public, then in the __init__.py file do: 如果您确定了一个constants模块,我会添加一个__all__序列来说明哪些值是公共的,然后在__init__.py文件中执行:

from constants import *

to make the same names available at the package level. 在包级别提供相同的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM