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

查看:31
本文介绍了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天全站免登陆