我有C的背景,但现在用Python3.x做了大量的科学计算工作,所以我想了解一下我的风格或口音在Python标准中有多“怪异”。在
特别是,Python中没有const
这样的东西,这让我感到无穷无尽。我的用例是这样的:我保存*.npz
文件(numpy序列化的数据字典),传递dicts,写入文件等,并且字典键、文件名等需要有一个一致的、可靠的命名模式。在
很明显,在8个地方输入相同的魔法愚蠢字符串是错误的。在
所以在我的模块根目录中,我有一个通常称为base.py
的文件:
import os
from collections import namedtuple
from os import path
# This is the tuple that contains operational constants
RuntimeConstants = namedtuple("Const", " ModelDirectoryLabelName \
DefaultModelOutputDirectoryRoot \
ResultDirectoryNameFormat \
PeripheryOutputFilePrefix \
NCOutputFilePrefix \
SummaryPlotFileName \
PeripheryConfigurationName \
ResourceDirectoryName \
StimulusTemplateName")
runtime_consts = RuntimeConstants(ModelDirectoryLabelName=".model-output-root",
DefaultModelOutputDirectoryRoot="model-output",
ResultDirectoryNameFormat="%d %b %y - %H%M",
PeripheryOutputFilePrefix="periphery-output-",
NCOutputFilePrefix="nc-output-",
PeripheryConfigurationName="simulation-configuration.yaml",
SummaryPlotFileName="summary-plots.pdf",
ResourceDirectoryName="resources",
StimulusTemplateName="default_stimulus.yaml"
)
# This is the path of __this file__, which we can then base location on
rootPath = os.path.dirname(os.path.abspath(__file__))
元组是不可变的;命名元组有语义上有意义的标记,现在:
在c中,用public static const string Foo = "some magic string value";
填充一个或多个Constants
类是很正常的做法,所以我在这里尝试重新创建。在
我现在有4个这样的namedtuples
在base.py
中,这看起来好像有太多了——但我不需要更多。它们在语义上都是不同的——我根据useage关联对常量进行分组。在
这是常见的ish做法吗?在
不是的。常量的标准约定是只使用所有大写字母的名称来表示值是常量,将它们记录为常量。在
模块的用户修改这些值的风险由自己承担。在
如果常量与类自然相关,那么它们可以是类属性,而不是模块级全局变量,但创建类只是来对这些值进行分组并不常见。在
相关问题 更多 >
编程相关推荐