在Python中实现可观察集合的推荐方法? [英] Recommented way to implement observable collections in Python?

查看:70
本文介绍了在Python中实现可观察集合的推荐方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Python中有一些可观察的集合/序列,使我能够侦听变更事件,例如添加新项目或更新项目:

I would like to have some observable collections/sequences in Python that allow me to listen on change events, like for adding new items or updating items:

list = ObservableList(['a','b','c'])
list.addChangeListener(lambda new_value: print(new_value))
list.append('a') # => should trigger the attached change listener

data_frame = ObservableDataFrame({'x': [1,2,3], 'y':[10,20,30]})
data_frame.addChangeListener(update_dependent_table_cells) # => allows to only update dependent cells instead of a whole table

A.我发现以下项目提供了可观察的集合的实现,并且看起来很有希望:

A. I found following project that provides implementations of observable collections and looks quite promising:

https://github.com/dimsf/Python-observable-collections

它可以满足我的要求

from observablelist import ObservableList

def listHandler(event):
    if event.action == 'itemsUpdated':
        print event.action + ', old items: ' + str(event.oldItems) + ' new items: ' + str(event.newItems) + ' at index: ' + str(event.index)
    elif event.action == 'itemsAdded' or event.action == 'itemsRemoved':
        print(event.action + ', items: ' + str(event.items) + ' at index: ' + str(event.index))

myList = ObservableList()
myList.attach(listHandler)

#Do some mutation actions, just like normal lists.
myList.append(10)
myList.insert(3, 0)

但是,最后一次更改是6年前,我想知道是否还有其他更新或使用Python替代版本构建?

However, the last change is 6 years ago and I am wondering if there are some more up to date or build in Python alternatives?

B.我还发现了RxPy: https://github.com/ReactiveX/RxPY

B. I also found RxPy: https://github.com/ReactiveX/RxPY

import rx
list = ["Alpha", "Beta", "Gamma"]
source = rx.from_(list)
source.subscribe(
   lambda value: print(value),
   on_error = lambda e: print("Error : {0}".format(e)),
   on_completed = lambda: print("Job Done!")
) 

是否可以使订阅保持打开状态,以便在订阅之后将新值添加到列表 中?虚拟代码:

Is it somehow possible, to keep the subscription open, so that I am able to append new values to the list after the subscription? Dummy code:

source.subscribe(..., keep_open = True)
source.append("Delta")  # <= does not work; there is no append method
source.close()

换句话说:我可以/应该将RxPy源用作可观察的集合吗?

With other words: can/should I use RxPy sources as observable collections?

C.Python中似乎存在许多不同的可能性来处理事件和实现观察者模式:

C. There seem to exist many different possibilities in Python to handle events and implement observer patterns:

Python中的事件系统

Python观察者模式:示例,提示?

在python中实现观察者模式的替代方法

使用装饰器在Python3中实现观察者模式

=>在Python中实现可观察集合的推荐/Python方法是什么?我应该使用(过时的)A.还是B.的改型(似乎有不同的目的?)甚至是C的另一种策略?

=> What is the recommented/pythonic way to implement observable collections in Python? Should I use (outdated?) A. or an adapted form of B. (which seems to serve a different purpose?) or even another strategy from C.?

=>是否有计划以某种方式标准化这种可能性,并直接在Python中包括默认的可观察集合?

=> Are there plans to somehow standardize that possibilities and include default observable collections directly in Python?

有关DataFrames的相关问题:

Related question, specific to DataFrames:

如何制作表格/电子表格(例如pandas DataFrame),可以使用触发器还是更改事件?

推荐答案

我从未使用过RxPy,但它似乎是非常接近js/ts的rx模式的实现.

I've never used RxPy but it seems to be an implementation of the rx pattern very close to the js/ts one.

首先,您想拥有一个可观察的对象,并且您都可以使用它来将数据推送到它和观察者中.这是主题,可能是行为主题或重播主题.创建主题,然后使用on_next()运算符在其中添加新值.

First you want to have an observable that you both use to push data into it and observer. That's a subject, potentially a behaviour subject or replay subject. Create the subject, then push new values in it using the on_next() operator.

对于您的第二个问题,您似乎想合并"一个问题.将多个可观察变量合并为一个可观察变量.有多种方法可以执行此操作,但是最有可能的是,您正在寻找的是CombineLatest或Concat.在操作员中抢劫.

For you second question, it seems that you want to "combine" multiple observables into one observable. There's multiple way to do this, but most likely, what you're looking for is CombineLatest or Concat. Loot at the operators.

如果我举第二个例子,代码将如下所示:

If I take your second example the code will look like that:

from rx.subject.subject import Subject

list = ["Alpha", "Beta", "Gamma"]
# assuming that you want each item to be emitted one after the other
subject = Subject()
subject.subscribe(
    lambda value: print(value),
    on_error = lambda e: print("Error : {0}".format(e)),
    on_completed = lambda: print("Job Done!")
)
subject.on_next('Alpha')
subject.on_next('Beta')
subject.on_next('Gamma')
subject.on_next('Delta')

如果使用BehaviourSubject,则将能够提供初始值,并且当新的观察者订阅时,它将接收最后发出的值.如果您使用ReplaySubject,则可以提供值,然后进行订阅,观察者将接收到该对象到目前为止发出的所有值.

If you use a BehaviourSubject, you will be able to provide an initial value, and when a new observer subscribe, it will receive the last emitted value. If you use a ReplaySubject you can provide values, then subscribe, the observer will receive all the values that the subject emitted up to this point.

这篇关于在Python中实现可观察集合的推荐方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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