Python:将模块及其变量视为单例—干净的方法? [英] Python: thinking of a module and its variables as a singleton — Clean approach?

查看:119
本文介绍了Python:将模块及其变量视为单例—干净的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的Python程序中实现某种单例模式.我当时正在考虑不使用类就可以做到这一点.也就是说,我想将所有与单例相关的函数和变量放在模块中,并认为它是实际的单例.

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-related functions and variables within a module and consider it an actual singleton.

例如,说这将在文件"singleton_module.py"中:

For example, say this is to be in the file '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 = ...

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

Then, the rest of the program (i.e., other modules) would use this singleton like so:

# 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

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

This seemed to be a pretty good idea to me, because it looks pretty clean in the modules that use the singleton.

但是,单例模块中所有这些乏味的全局"语句都很丑陋.它们出现在处理与单例相关的变量的每个函数中.在这个特定的示例中,这没什么大不了的,但是当您有10个以上的变量要在多个函数中进行管理时,那就不妙了.

However, all these tedious 'global' statements in the singleton module are ugly. They occur in every function that processes the singleton-related variables. That's not much in this particular example, but when you have 10+ variables to manage across several functions, it's not pretty.

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

Also, this is pretty error-prone if you happen to forget the global statements: variables local to the function will be created, and the module's variables won't be changed, which is not what you want!

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

So, would this be considered to be clean? Is there an approach similar to mine that manages to do away with the 'global' mess?

或者这根本不是可行的方法吗?

Or is this simply not the way to go?

推荐答案

使用模块作为单例的常见替代方法是Alex Martelli的

A common alternative to using a module as a singleton is Alex Martelli's Borg pattern:

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

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

There can be multiple instances of this class, but they all share the same state.

这篇关于Python:将模块及其变量视为单例—干净的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆