使用namedtuples作为事实上的const是聪明还是愚蠢?

2024-04-20 16:37:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有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个这样的namedtuplesbase.py中,这看起来好像有太多了——但我不需要更多。它们在语义上都是不同的——我根据useage关联对常量进行分组。在

这是常见的ish做法吗?在


Tags: 模块文件path字符串pyimportoutputbase
1条回答
网友
1楼 · 发布于 2024-04-20 16:37:10

不是的。常量的标准约定是只使用所有大写字母的名称来表示值是常量,将它们记录为常量。在

MODEL_DIRECTORY_LABEL_NAME = ".model-output-root"
DEFAULT_MODEL_OUTPUT_DIRECTORY_ROOT = "model-output"
# etc

模块的用户修改这些值的风险由自己承担。在

如果常量与类自然相关,那么它们可以是类属性,而不是模块级全局变量,但创建类只是来对这些值进行分组并不常见。在

相关问题 更多 >