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

(Niko Gamulin) #1

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!

0 Likes

(Akash Palrecha) #2

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.

3 Likes

(Niko Gamulin) #3

Thanks!

0 Likes

(Michael) #4

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