sharkyenergy
sharkyenergy

Reputation: 4183

python - how to store settings in memory?

I'm totally new to Python, and I am trying to figure out a way to store settings. My application (python + pyqt5) stores the settings in a SqLite database. A function loads these settings at startup and sets all the textboxes and checkboxes accordingly.

Based on the settings, my program does have to reacti differently. My program works on multiple threads, and all these threads need to know the pertinent settings. I do not want to access the UI each time I need a setting, i would like to have the value stored in a variable, and have this variable accessible from the whole app. (read only is enough...)

Now, this is what i see in my head, but now I would like to know if this makes even sense, if there is a different way to do it, that is better, if there is something like a "global environment variable" that can be read from everywhere?

I searched online, but was not able to find any information to this.

what options I explored so far:

Upvotes: 1

Views: 771

Answers (1)

gimix
gimix

Reputation: 3833

You may define an "environment" object in your main thread, and pass it to all your threads/tasks. For instance:

from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from random import randint

@dataclass
class MyEnv():
    mynumber : int = 0

def setup_task(env):
    env.mynumber = randint(0,10)
    return(f'setting the magic number to {env.mynumber}')

def normal_task(env):
    return(f'the magic number is currently {env.mynumber}')

myenv = MyEnv()

with ThreadPoolExecutor(10) as executor:
        for future in [executor.submit(task, myenv) for i in range(10) for task in [setup_task, normal_task]]:
            print(future.result())
----
setting the magic number to 1
the magic number is currently 1
setting the magic number to 1
the magic number is currently 1
setting the magic number to 9
the magic number is currently 9
setting the magic number to 3
the magic number is currently 3
setting the magic number to 4
the magic number is currently 4
setting the magic number to 0
the magic number is currently 0
setting the magic number to 8
the magic number is currently 8
setting the magic number to 2
the magic number is currently 2
setting the magic number to 1
the magic number is currently 1
setting the magic number to 10
the magic number is currently 10

Upvotes: 1

Related Questions