Reputation: 191
I have a function that returns a dictionary.
I would like to be able to access and work with that dictionary many times in the code, without the need to be calling the function that produces that dictionary every time. In other words, call the function once, but work with the dictionary that it returns many times.
So this way, the dictionary is constructed only once (and maybe stored somewhere?), but called and utilised many times in the script.
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.
I have read other posts such as: Access a function variable outside the function without using `global`
But I am not sure that by declaring the dictionary as global withing the function_to_produce_dict() is going to make the dictionary accessible without having to build it every time, by calling the function again and again.
Is this possible?
Upvotes: 1
Views: 4863
Reputation: 20705
It's a little unclear what is stopping you from just using the dictionary as usual. Do you have a situation such as the following?
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()
In such a case, you might want foo
and bar
to take an argument that is an already-constructed dct
:
def foo(dct):
# do something with dct
If you really can't get around it, you can cache the result of creating the dictionary so that it's really only computed once:
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()
This is just a specialized memoization decorator... you could get a lot fancier, use functools.partial
to preserve function metadata, etc.
Upvotes: 2
Reputation: 12022
Maybe I'm not understanding, but you're already saving it in create_dict
; just continue to use the dict in create_dict
. It's not being constructed each time once you store it in create_dict
.
Perhaps you should rename it, as create_dict
sounds like a function that creates a dict. Maybe that's related to your confusion on this?
Upvotes: 5