Python: thinking of a module and its variables as a singleton — Clean approach?

后端 未结 6 2087
被撕碎了的回忆
被撕碎了的回忆 2020-12-13 13:21

I\'d like to implement some sort of singleton pattern in my Python program. I was thinking of doing it without using classes; that is, I\'d like to put all the singleton-rel

6条回答
  •  自闭症患者
    2020-12-13 13:39

    Building off of WillYang's answer and taking it a step further for cleanliness: define a simple class to hold your global dictionary to make it easier to reference:

    class struct(dict):
        def __init__(self, **kwargs):
            dict.__init__(self, kwargs)
            self.__dict__ = self
    
    g = struct(var1=None, var2=None)
    
    def func():
        g.var1 = dict()
        g.var3 = 10
        g["var4"] = [1, 2]
        print(g["var3"])
        print(g.var4)
    

    Just like before you put anything you want in g but now it's super clean. :)

提交回复
热议问题