Python 观察者模式:示例、技巧? [英] Python Observer Pattern: Examples, Tips?

查看:18
本文介绍了Python 观察者模式:示例、技巧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有用 Python 实现的 GoF Observer 的示例?我有一个位代码,目前有一些调试代码通过关键类(如果设置了魔法环境,当前生成到 stderr 的消息).此外,该类有一个接口,用于增量返回结果以及将它们存储(在内存中)以进行后期处理.(该类本身是一个作业管理器,用于通过 ssh 在远程机器上并发执行命令).

Are there any exemplary examples of the GoF Observer implemented in Python? I have a bit code which currently has bits of debugging code laced through the key class (currently generating messages to stderr if a magic env is set). Additionally, the class has an interface for incrementally return results as well as storing them (in memory) for post processing. (The class itself is a job manager for concurrently executing commands on remote machines over ssh).

目前该类的用法类似于:

Currently the usage of the class looks something like:

job = SSHJobMan(hostlist, cmd)
job.start()
while not job.done():
    for each in job.poll():
        incrementally_process(job.results[each])
        time.sleep(0.2) # or other more useful work
post_process(job.results)

另一种使用模式是:

job = SSHJobMan(hostlist, cmd)
job.wait()  # implicitly performs a start()
process(job.results)

这对于当前的实用程序来说一切正常.然而,它确实缺乏灵活性.比如我目前支持一个简短的输出格式或者一个进度条作为增量结果,我也支持post_process() 函数的简短、完整和合并消息"输出.

This all works fine for the current utility. However it does lack flexibility. For example I currently support a brief output format or a progress bar as incremental results, I also support brief, complete and "merged message" outputs for the post_process() function.

但是,我想支持多个结果/输出流(终端的进度条、日志文件的调试和警告、成功作业的输出到一个文件/目录、错误消息和其他不成功的结果工作到另一个,等等).

However, I'd like to support multiple results/output streams (progress bar to the terminal, debugging and warnings to a log file, outputs from successful jobs to one file/directory, error messages and other results from non-successful jobs to another, etc).

这听起来像是需要观察者的情况……让我的类的实例接受来自其他对象的注册,并在发生特定类型的事件时将它们回调.

This sounds like a situation that calls for Observer ... have instances of my class accept registration from other objects and call them back with specific types of events as they occur.

我正在查看 PyPubSub,因为我在 SO 相关问题中看到了一些对此的引用.我不确定我是否准备好将外部依赖项添加到我的实用程序中,但我可以看到使用他们的界面作为我的模型的价值,如果这会让其他人更容易使用.(该项目既是一个独立的命令行实用程序,也是一个用于编写其他脚本/实用程序的类).

I'm looking at PyPubSub since I saw several references to that in SO related questions. I'm not sure I'm ready to add the external dependency to my utility but I could see value in using their interface as a model for mine if that's going to make it easier for others to use. (The project is intended as both a standalone command line utility and a class for writing other scripts/utilities).

简而言之,我知道如何做我想做的事……但有很多方法可以实现.从长远来看,我想要关于什么最有可能对代码的其他用户起作用的建议.

In short I know how to do what I want ... but there are numerous ways to accomplish it. I want suggestions on what's most likely to work for other users of the code in the long run.

代码本身位于:classh.

推荐答案

但是它确实缺乏灵活性.

However it does lack flexibility.

嗯……实际上,如果您想要异步 API,这对我来说是一个不错的设计.它通常是.也许你需要的只是从 stderr 切换到 Python 的 logging模块,它有一种自己的发布/订阅模型,还有 Logger.addHandler() 等等.

Well... actually, this looks like a good design to me if an asynchronous API is what you want. It usually is. Maybe all you need is to switch from stderr to Python's logging module, which has a sort of publish/subscribe model of its own, what with Logger.addHandler() and so on.

如果您确实想支持观察者,我的建议是保持简单.你真的只需要几行代码.

If you do want to support observers, my advice is to keep it simple. You really only need a few lines of code.

class Event(object):
    pass

class Observable(object):
    def __init__(self):
        self.callbacks = []
    def subscribe(self, callback):
        self.callbacks.append(callback)
    def fire(self, **attrs):
        e = Event()
        e.source = self
        for k, v in attrs.iteritems():
            setattr(e, k, v)
        for fn in self.callbacks:
            fn(e)

您的作业类可以子类化 Observable.当感兴趣的事情发生时,调用 self.fire(type="progress", percent=50) 等.

Your Job class can subclass Observable. When something of interest happens, call self.fire(type="progress", percent=50) or the like.

这篇关于Python 观察者模式:示例、技巧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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