traitlets icon indicating copy to clipboard operation
traitlets copied to clipboard

Feature request: combine callback calls after holding notifications

Open astrofrog opened this issue 8 years ago • 2 comments

In the following example:

from traitlets import HasTraits, Integer

class State(HasTraits):
    a = Integer()
    b = Integer()

def callback(*args, **kwargs):
    print(args, kwargs)

s = State()
s.observe(callback)
with s.hold_trait_notifications():
    s.a = 1
    s.b = 2

Callback gets called twice. However, it would be nice to have a way to minimize the number of callback calls when exiting the context manager.

The reason I ask about this is because I would like to consider transitioning glue from using echo, which is our own trait-like library by traitlets. The case I describe above is common in our code, where we change a bunch of traits and then want to e.g. force a redraw (but only one and not one per trait).

astrofrog avatar Aug 27 '17 12:08 astrofrog

@astrofrog, I don't think there's a good way to do this - it's hard (if not impossible) to infer whether the user does, or doesn't want to squash notifications to the same callback. Especially if they come from different traits.

It might be better if users had more control over notification contexts in general:

def squasher(self, cache):
    """The cache contains all the notifications incurred in the context"""
    # implement your own custom squashing logic.
    return cache

with x.manage_notifications(squasher):
    x.a = 1
    x.b = 2

The above probably isn't the best way to accomplish this though.

rmorshea avatar Aug 28 '17 20:08 rmorshea

@rmorshea - I agree that I think the real solution here is probably to have a more generic mechanism where I can choose to implement this behavior. This could be an optional argument to hold_notifications potentially?

astrofrog avatar Aug 28 '17 22:08 astrofrog