How can I share a (global) variable between different custom python modules.

15 views
Skip to first unread message

piyush kirtivardhan

unread,
Jul 10, 2024, 6:32:24 AM7/10/24
to Salt-users
code sample:
# Define the global dictionary
global_dict = {}

def update_global_dict(key, value):
    """
    Update the global dictionary with the given key-value pair.
    """
    global global_dict
    global_dict[key] = value
    print(f"Updated global_dict: {global_dict}")

def fetch_from_global_dict(key):
    """
    Fetch the value from the global dictionary for the given key.
    """
    global global_dict
    return global_dict.get(key, "Key not found")
----------------------------------------------------------------------------------------
I am using the below way to achieve it.

def update_global_dict(key, value):
    __salt__['data.update'](key, pickle.dumps(value))


def fetch_from_global_dict(key):
    status = __salt__['data.has_key'](key)
    return pickle.loads(status)

but there are some issue in performance:
when i am try to access it multiple time:
it throwing error in deserialization and serialization error.

is there any way to so we can achieve the values in global variable so i don't have any problem in  fetch and storing the data in custom python modules?
Saving in file and opening and reading file again is not an option.

Reply all
Reply to author
Forward
0 new messages