hit counter


My development logbook

Side Effect Programming Is Bad

This bit of code is trying to calculate a list of mid prices based on bid and ask prices

def mids(self, bids, asks):
    f = lambda X, Y: (X is not None) and (Y  is not None) and (X+Y)/2 or None
    return [f(bid, ask) for bid, ask in zip(bids, asks)

It works fine unTIL one day there is a None in mids.

The bid and ask of the corresponding item are both zero. We expect to see zero in the result.

So what happened?

The original lambda, f, rely on the side effect of short-circuit behaviour of and/or operator to return the mid price (if there is data) or None (if both are None)

But it will not work if both X and Y are zero, because zero is evaluated to false. While zero is the answer we want, the execution falls to the ‘or’ part of the expression.

A better to write the lambda:

f = lambda X, Y:  (X+Y)/2.0 if (X is not None) and (Y  is not None)  else None