如何在函数外部访问函数内生成的字典,而不必多次调用函数。 PYTHON

时间:2015-08-09 23:33:37

标签: python function dictionary

我有一个返回字典的函数。

我希望能够在代码中多次访问和使用该字典,而无需每次都调用生成该字典的函数。换句话说,调用函数一次,但使用它返回多次的字典。

所以这样,字典只构造一次(并且可能存储在某个地方?),但在脚本中多次调用和使用。

def function_to_produce_dict():
    dict = {}
    # something
    # something that builds the dictionary 
    return dict 


create_dict = function_to_product_dict()

# other code that will need to work with the create_dict dictionary. 
# without the need to keep constructing it any time that we need it. 

我已阅读其他帖子,例如: Access a function variable outside the function without using `global`

但是我不确定通过将函数声明为全局而使用function_to_produce_dict()将通过一次又一次地调用函数来使字典无需每次构建都可访问。

这可能吗?

2 个答案:

答案 0 :(得分:5)

也许我不理解,但你已经将它保存在overhead/memory;继续使用create_dict中的字典。一旦将其存储在create_dict中,它就不会被构建。

也许您应该重命名它,因为create_dict听起来像是一个创建字典的函数。也许这与你对此的困惑有关?

答案 1 :(得分:2)

有点不清楚是什么阻止你像往常一样使用字典。你有这样的情况吗?

def function_to_produce_dict():
    ...

def foo():
    dct = function_to_produce_dict()
    # do something to dct
    ...

def bar():
    dct = function_to_produce_dict()
    # do something to dct
    ...

foo()
bar()

在这种情况下,您可能希望foobar采用已构建的dct参数:

def foo(dct):
    # do something with dct

如果真的无法绕过它,您可以缓存创建字典的结果,以便它实际上只计算一次:

def _cached_function_to_compute_dict():
    dct = None
    def wrapper():
        if dct is None:
            dct = _function_to_compute_dict()
        return dct
    return wrapper

def _function_to_compute_dict():
    # create and return a dictionary
    return dct

function_to_compute_dict = _cached_function_to_compute_dict()

这只是一个专门的memoization装饰器......你可以获得更多的爱好者,使用functools.partial来保存功能元数据等。

相关问题