Monday, 27 June 2022

Best way to initialize variable in a module?

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?

  1. 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.

  1. Get reference first time the dataset is needed, save in global variable, and access with get_dataset() method

    dataset = None
    
    def get_dataset():
        global dataset
        if dataset is none
            dataset = #get dataset from internet
        return dataset
    
  2. Get reference first time the dataset is needed, save as function attribute, and access with get_dataset() method

    def get_dataset():
        if not hasattr(get_dataset, 'dataset'):
            get_dataset.dataset = #get dataset from internet
        return get_dataset.dataset
    
  3. Any other way



from Best way to initialize variable in a module?

No comments:

Post a Comment