Arun
Arun

Reputation: 1179

Make a global dict object in python which can access and edit from any py files

I want keep some global data which can access and edit from any python files. I tried with python classes but it is not working across the files the code is given below.(Note :I am not interested to do any file operations)

class Settings(object):
    """docstring for Settings"""
    device = None
    def __init__(self, *args, **kwargs):
        if Settings.device is None:
            Settings.device = DeviceSettings()



class DeviceSettings(object):
    def __init__(self, *args, **kwargs):
        self.mode = None
        self.ops = []
        self.phyops = None

Settings()
Settings.device

Upvotes: 1

Views: 1352

Answers (3)

saloua
saloua

Reputation: 2493

You can achieve that by making the class Settings a Singleton Note that in order to access device you need to do self.device instead of Settings.device

def singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance

class DeviceSettings(object):
    def __init__(self, *args, **kwargs):
        self.mode = None
        self.ops = []
        self.phyops = None

@singleton
class Settings(object):
    """docstring for Settings"""
    device = None
    def __init__(self, *args, **kwargs):
        if self.device is None:
            self.device = DeviceSettings()




x = Settings()
print x.device

# In an another file y.device will return the last device value.
x.device = "Another device"
y = Settings()
print y.device

Upvotes: 0

hspandher
hspandher

Reputation: 16753

Dictionaries are mutable by default. You don't need to write a class for it.

# common.py
common_data = {
}

# file1.py
from common import common_data
common_data['key'] = 'value'

Now the important question, you need to ask is, is it advisable to use a global variable for mutation.

Upvotes: 0

Netwave
Netwave

Reputation: 42786

Im not a fan of this but if you really need it just create a global dict in a module and then import it:

#a.py

MY_GLOBAL_DICT = {}

#b.py

from a import MY_GLOBAL_DICT
MY_GLOBAL_DICT["hey"] = 10

Here you have a working example

Upvotes: 1

Related Questions