在几个不相关的函数中使用常量的正确方法

时间:2017-05-04 17:57:37

标签: python oop functional-programming

我想将一些变量视为常量,因为它们永远不会改变,并且在我的项目中被大量不同的函数使用。我需要能够从几个不同的模块中访问常量,我发现的建议建议将常量放入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?

1 个答案:

答案 0 :(得分:1)

是的,你可以做到这一点,这很常见。同样常见且通常更方便的是使用/ abuse class作为命名空间,因此您有一件事要导入,一个地方可能会改变常量的工作方式。我做的事情如下:

class Settings(object):
    TIMEOUT = 4
    RETRY = 2
    SECRET_KEY = 'foobar'

然后你可以导入设置,传递它,或者如果你以后需要,甚至可以通过使用getattr或metaclass hackery来改变你要求或设置Settings.FOO时发生的事情。只是一个很好的未来证明。

相关问题