【发布时间】:2017-10-03 00:57:15
【问题描述】:
我有一些变量我想将其视为常量,因为它们永远不会改变,并且在我的项目中被大量不同的函数使用。我需要能够从几个不同的模块访问常量,我发现的建议建议将常量放入我的config.py,然后在每个模块中使用from config import CONSTANT1。
我的问题是:我不确定在这种情况下实际使用常量的最 Pythonic 方式吗?以下示例选项是否正确,或者可能取决于您要执行的操作?有没有其他我没想到的正确方式?
def fake_function(x, y):
# Problem: function relies on the module-level environment for an input
# (Seems sloppy)
return (x + y + CONSTANT1)
def fake_function2(x, y, z=CONSTANT1):
# Problem: seems redundant and as if there was no point in declaring a constant
# Also you end up with way too many parameters this way
return (x + y + z)
class Fakeness(object):
def __init__(self):
self.z = CONSTANT1
def fake_sum(self, x, y):
return (x + y + self.z)
# Problem: I suspect this might be the correct implementation - but
# I hope not because my understanding of OOP is weak :) I also don't
# think this helps me with my many functions that have nothing to do
# with each other but happen to use the same constants?
【问题讨论】:
-
我不明白你认为第一个选项有什么问题。
-
我真的只是在检查它是否被认为是正确的:) 我对函数的理解在某种程度上受到
R和阅读函数式编程的影响,我已经关于是否适合完全依赖全局(或在本例中为模块级)环境,或者函数是否需要自包含,有点混乱。我也有兴趣开始对我的工作进行单元测试(我还不知道该怎么做),我不清楚依赖常量是否是一个坏主意/最终会引入难以理解的错误跨度> -
IME 单元测试只有在你依赖 mutable 全局状态时才会变得复杂。常量在程序的生命周期内不会改变,因此在函数中引用它们不会增加潜在代码路径的数量。在这方面,它们并不比直接使用文字值差。
-
您可能会发现标题为 Constants in Python 的 ActiveState 配方很有用。
-
很有帮助,感谢 martineau 和 Kevin。找到了一些关于可变全局状态的好信息(比如link),进一步澄清了事情 - 我很欣赏这些参考资料和关键词
标签: python oop functional-programming