Python:将模块及其变量视为单例 - Clean方法?

32 python singleton module

我想在我的Python程序中实现某种单例模式.我想在不使用课程的情况下这样做; 也就是说,我想将所有与单例相关的函数和变量放在一个模块中,并将其视为一个实际的单例.

例如,假设这是在'singleton_module.py'文件中:

# singleton_module.py

# Singleton-related variables
foo = 'blah'
bar = 'stuff'

# Functions that process the above variables
def work(some_parameter):
    global foo, bar
    if some_parameter:
        bar = ...
    else:
        foo = ...
Run Code Online (Sandbox Code Playgroud)

然后,程序的其余部分(即其他模块)将使用此单例,如下所示:

# another_module.py

import singleton_module

# process the singleton variables,
# which changes them across the entire program
singleton_module.work(...)

# freely access the singleton variables
# (at least for reading)
print singleton_module.foo
Run Code Online (Sandbox Code Playgroud)

这对我来说似乎是个好主意,因为它在使用单例的模块中看起来很干净.

然而,单身模块中所有这些繁琐的"全局"陈述都是丑陋的.它们出现在处理单例相关变量的每个函数中.在这个特定的例子中,这并不多,但是当你有10个以上的变量来管理多个函数时,它并不漂亮.

此外,如果您忘记了全局语句,这很容易出错:将创建函数本地的变量,并且不会更改模块的变量,这不是您想要的!

那么,这会被认为是干净的吗?是否有类似于我的方法可以消除"全球"混乱?

或者这根本不是要走的路?

Sve*_*ach 24

使用模块作为单身人士的常见替代方案是Alex Martelli的Borg模式:

class Borg:
    __shared_state = {}
    def __init__(self):
        self.__dict__ = self.__shared_state
    # and whatever else you want in your class -- that's all!
Run Code Online (Sandbox Code Playgroud)

此类可以有多个实例,但它们都共享相同的状态.


小智 7

也许你可以把所有的变量放在一个全局字典中,你可以直接在你的函数中使用这个字典而不需要“全局”。

# 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'] = ...
Run Code Online (Sandbox Code Playgroud)

为什么你可以这样做是Python Scopes 和 Namespaces