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

后端 未结 6 2100
被撕碎了的回忆
被撕碎了的回忆 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:40

    Maybe you can put all the variables in a global dict, and you can directly use the dict in your functions without "global".

    # Singleton-related variables
    my_globals = {'foo': 'blah', 'bar':'stuff'}
    
    # Functions that process the above variables
    def work(some_parameter):
        if some_parameter:
            my_globals['bar'] = ...
        else:
            my_globals['foo'] = ...
    

    why you can do it like this is Python Scopes and Namespaces.

提交回复
热议问题