Let's say I need to write incoming data into a dataset on the cloud. When, where and if I will need the dataset in my code, depends on the data coming in. I only want to get a reference to the dataset once. What is the best way to achieve this?
-
Initialize as global variable at start and access through global variable
if __name__="__main__": dataset = #get dataset from internet
This seems like the simplest way, but initializes the variable even if it is never needed.
-
Get reference first time the dataset is needed, save in global variable, and access with
get_dataset()
methoddataset = None def get_dataset(): global dataset if dataset is none dataset = #get dataset from internet return dataset
-
Get reference first time the dataset is needed, save as function attribute, and access with
get_dataset()
methoddef get_dataset(): if not hasattr(get_dataset, 'dataset'): get_dataset.dataset = #get dataset from internet return get_dataset.dataset
-
Any other way
from Best way to initialize variable in a module?
No comments:
Post a Comment