[Solved] Initialize variables when they’re not already declared in python


One solution is to use a defaultdict:

from collections import defaultdict

my_dict = defaultdict(lambda: [])
my_dict['var1'].append(1)
print(my_dict['var1'])  # prints '[1]'

This would not allow you to simply do print(var1), however, because it would still be undefined in your local (or global) namespace as a tagged value. It would only exist in the defaultdict instance as key.

Another option would be to use a class:

class TaskRunner:
    def __init__(self, var1=None, var2=None, var3=None):
        self.var1 = var1 or [] 
        self.var2 = var2 or []
        self.var3 = var3 or []


    def run_scheduled(self):
        for i in [self.var1, self.var2, self.var3]:
            i.append(random.randrange(1, 10000000))

runner = TaskRunner()
schedule.every(60).seconds.do(runner.run_scheduled)

You can also use pickle to save instances to load later (i.e., in subsequent runs of your job).

7

solved Initialize variables when they’re not already declared in python