【发布时间】:2021-05-02 12:29:00
【问题描述】:
我想在 Python 中有一些可观察的集合/序列,让我能够监听更改事件,例如添加新项目或更新项目:
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. 我发现以下项目提供了可观察集合的实现,并且看起来很有希望:
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 替代方案?
B.我还发现了 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!")
)
是否有可能保持订阅打开,以便我能够在订阅之后将新值附加到列表中?虚拟代码:
source.subscribe(..., keep_open = True)
source.append("Delta") # <= does not work; there is no append method
source.close()
换句话说:我可以/应该使用 RxPy 源作为可观察的集合吗?
C. Python 中似乎存在许多不同的可能性来处理事件和实现观察者模式:
Python Observer Pattern: Examples, Tips?
alternate ways to implement observer pattern in python
Using decorators to implement Observer Pattern in Python3
=> 在 Python 中实现可观察集合的推荐/pythonic 方法是什么?我应该使用(过时的?)A. 还是 B. 的改编形式(似乎有不同的目的?)甚至 C. 的另一种策略?
=> 是否有计划以某种方式标准化这些可能性并直接在 Python 中包含默认的 observable 集合?
相关问题,特定于 DataFrames:
How to make tables/spreadsheets (e.g. pandas DataFrame) observable, use triggers or change events?
【问题讨论】:
标签: python collections observable sequence observer-pattern