Hi, I’ve created a small notebook to illustrate my confusion:
tl;dr: I want to reset a mutable variable when one of it’s dependencies changes.
Hi, I’ve created a small notebook to illustrate my confusion:
tl;dr: I want to reset a mutable variable when one of it’s dependencies changes.
Things are usually simpler if you avoid mutable state. Here’s an alternative:
The toggle_boxes
are as before (though, I implemented them by hand rather than using Jeremy’s inputs). Now, though, I’ve combined the Sample and Reset buttons into a single view whose value is the array of observations. When you click Sample, it adds a random observation to the array, and when you click Reset, it clears the observation array.
In addition, since the observations
cell references toggle_boxes
, the observations are automatically cleared when you toggle a checkbox.
Using the notebook visualizer, we can compare the two approaches.
Before:
After:
Hi Bryan,
Although avoiding mutable state is always the cleaner and less tangled way to go … sometimes you just want some of that dirty, dirty mutability.
Here’s the minimal change your original notebook needs to stop taking samples when you don’t intend to:
In short, because you were referencing toggle_boxes
reactively, you were sampling whenever the toggle boxes changed. Directly accessing viewof toggle_boxes.value
avoids this unwanted reactivity.
Thank you so much! It took a bit more fenagling to actually get what I wanted, but I was able to fix it up with this.
I really appreciate you showing me the “simplest” way. One slight gotcha: this doesn’t clear the mutable array when I change the toggled boxes.
Thanks again!
I see. (I thought that’s what the “Reset” button was for…)
Here’s an updated diff:
Note how your reset_button
cell now also observes toggle_boxes
. Whenever the toggle_boxes
value changes, the toggle_observations
array will be reset as well.
Ah! That’s great. Thanks for explaining how it works; I should have been able to figure this out, apologies.
I’m curious: Is this also a viable solution for appending to and resetting lists? (I only came upon this thread after I made it work!)
To be honest, I just spent about a couple of hours playing with this, and I’m still not sure I fully understand…getting it to work was more trial and error than anything else.
That certainly works, though I’m more fond of just handling things in a single cell like this: