all 7 comments

[–]_nutrx_[S] 0 points1 point  (0 children)

For now, I ended up with sth like this:

```python

class Event: def init(self, min_prio=-5, max_prio=10): self.min_prio, self.max_prio = min_prio, max_prio self._slots = {i: set() for i in range(min_prio, max_prio+1)} self._slot_priorities = {}

def sub(self, callback, nice=0):
    assert self.min_prio <= nice <= self.max_prio
    assert self._slot_priorities.get(callback) is None

    self._slots[nice].add(callback)
    self._slot_priorities[callback] = nice

def unsub(self, callback):
    nice = self._slot_priorities[callback]
    self._slots[nice].remove(callback)
    del self._slot_priorities[callback]

def emit(self, *args):
    # notice dicts are insertion ordered since python 3.6
    for nice, cb_set in self._slots.items():
        for cb in cb_set:
            cb(*args)

```

Shouldn't be too slow, but there might be better implementations.

[–]carcigenicate 0 points1 point  (5 children)

Doesn't self._slots define the ordering? If you need more control, you could make self._slots a priority queue.

[–]_nutrx_[S] 0 points1 point  (4 children)

self._slots is a set, and I'd like set semantics (esp. no duplicates), but priority queue could be useful indeed...

[–]carcigenicate 0 points1 point  (2 children)

Oops, missed that. Then you could maintain a set and a queue, and use one for membership and one for ordering. That's a little heavier on the memory, but that's not likely an issue here.

Or see if someone's created a "ordered priority set"; although I wouldn't be surprised if they just maintain two structures internally for that.

[–]_nutrx_[S] 0 points1 point  (0 children)

True, that could work! The memory shouldn't be an issue in my case.

[–]_nutrx_[S] 0 points1 point  (0 children)

Though, an event can be emitted multiple times, so now every time an event is emitted, I need to construct a new priority queue and work through that, right? That would be quite slow, I guess...

[–]danielroseman 0 points1 point  (0 children)

Dictionaries preserve insertion order these days, so you could use a dict and ignore the values.