簡體   English   中英

如何在函數外部訪問函數內部產生的字典,而又不需多次調用函數。 蟒蛇

[英]How to access a dictionary produced within a function, outside the function, without calling the function more than once. PYTHON

我有一個返回字典的函數。

我希望能夠在代碼中多次訪問並使用該詞典,而無需每次都調用生成該詞典的函數。 換句話說,一次調用該函數,但是使用它返回多次的字典。

因此,以這種方式,字典僅構建一次(也許存儲在某個地方?),但是在腳本中被調用和使用了很多次。

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. 

我讀過其他文章,例如: 不使用`global`即可訪問函數外部的函數變量

但是我不確定通過使用function_to_produce_dict()將字典聲明為全局字典,可以通過一次又一次地調用函數來使字典可訪問而不必每次都構建它。

這可能嗎?

也許我不太了解,但是您已經將其保存在create_dict 只需繼續使用create_dict的dict即可。 一旦將其存儲在create_dict就不會每次都在構造它。

也許您應該重命名它,因為create_dict聽起來像一個創建dict的函數。 也許這與您對此感到困惑有關?

尚不清楚是什么阻止您像往常一樣僅使用字典。 您是否遇到以下情況?

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()

這只是一個專門的備注裝飾器...您可能會覺得更有趣,可以使用functools.partial來保存函數元數據,等等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM