如何绕过不使用全局变量并传递太多参数?

时间:2012-06-28 04:48:14

标签: python global abstraction

这里要描述一些复杂的问题:

我想要一个函数AB(),它通过一个中间值将一个输入映射到另一个。更具体地说,该函数由两个函数组成,我们调用A()和B(),它们都返回字典(即A [B [输入]] - >结果)

这是我当前文件目录的一个示例:

packageX/

    __init__.py
    get_part_of_B_expensively.py
    something_that_will_use_convert.py
    convert.py
    packageA/

        __init__.py
        get_the_entirety_of_A_expensively.py

在我的convert.py中,我有以下内容:

import get_part_of_B_expensively
from packageA import get_the_entirety_of_A_expensively
dict_A = packageA.get_the_entirety_of_A_expensively()

def get_B():

    result = {}
    result = get_part_of_B_expensively() # this is a very expensive operation
    result += get_rest_of_B_inexpensively() # shorthand for adding two dictionaries
    return result # returns a dictionary

dict_B = get_B() # hence why i call it once outside, and not inside AB()

def AB(input):
    return dictA[dictB[input]]

不要认为这是正确的,因为我在定义get_B()之前无法初始化dict_B,并且我希望AB()的唯一参数是input,因为我想抽象它的实现。但是,我在全局介绍了一些变量,主要是dict_B和dictA,我不确定这是否是最好的方法。我可以将get_B()分离到它自己的包中,但我仍然会在全局框架中的某个地方调用它们。不知道这个方法应该是什么,我想尽可能少地调用A()和B()来调用同一个包中的文件,但是抽象函数AB()。

1 个答案:

答案 0 :(得分:3)

如果这是你的模块正在做的全部,我不会说保持这种方式是那么糟糕。对于仅处理特定数据的小脚本,有时使用全局是可以的,特别是如果您将其用作只读。 (当你需要改变它们或重新绑定它们时,会出现许多令人困惑的全局变量问题。)有许多可敬的库都有全局变量存储各种全局参数,例如从配置文件加载的自定义选项等。 / p>

对于更重量级的情况,如果你的任务更复杂,你可以创建一个基本上这样做的类:

class Convert(object):
    def __init__(self):
        self.A = packageA.get_the_entirety_of_A_expensively()
        self.B = getB() # or put get_B's code in here
    def AB(self, input):
        return self.A[self.B[input]]

converter = Convert()
converter.AB('blah')

如果您只需要做一件事情,这可能会有点过头了,但如果您需要参数化操作(例如,如果您有多个A和B序列可能需要操作),那么这就是可行的方法。 / p>