Don't understand res = res and... in CallbackHandler methods

Hi,

I am reimplementing the code and am wondering what do the following lines do:
for cb in self.cbs: res = res and cb.method_from_cb(learn)

why is the part ‘res = res and’ needed?
What would be different if the loop would be just:
for cb in self.cbs: cb.method_from_cb(learn)

I would appreciate if anyone explained this line.

Thanks!

In this particular context, all the callbacks present in self.cbs will be called on learn until one of them returns False. This is because there is an and conditional there which does not execute the expression on the right if the LHS is already false.
Essentially, the first callback that returns False will stop the execution of any other callback that comes after it.
If we change it as you suggest, we wouldn’t be able to stop other callbacks from executing in the case that we want to do it.

4 Likes

Thanks!

Very nice explanation!

Maybe FYI, this setup is called a „short-circuit operator“:
https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not

2 Likes

Later, in lesson 11, the call in Learner class is changed as shown below.
res .
Can anyone explain how does it work now, because now “res = cb(cb_name) and res”, so the callbacks are executed even though the previous one returned True.

I tried changing the call method of learner class to this:

.
Basically I changed the line res= cb(cb_name) and res to res = res or cb(cb_name) and then it worked as I expected. If any of the callback returned True it stopped the execution of following callbacks.