Below is a function from a driver that I wrote for and I2C temperature sensor. The function takes as input the name of the bus and the device's bus address, reads it's status register, and then reports the status verbosely. (It also returns a values of interest, but that's not important now).
I have two questions about this:
I'm using lots of
comment text {}'.format('this' if Condition else 'that')
. I gather this is frowned upon, but in this case I think readability is optimal. The alternative would bestatusthing = 'this' if Condition else 'that' 'comment text {}'.format(statusthing)
or, worse (as in 'much more lines and no better readability'):
if Condition: statusthing = 'this' else: statusthing = 'that' Rpt += 'comment text %s' % statusthing
Same for using this way of constructing the output string. I see people get upset when you do this:
Rpt = 'eggs, bacon, sausage \n' . . Rpt += 'sausage'
But in this case, it's concise, I think it's readable, it works. I don't see anything wrong with it. Is there?
Here's the full function.
def read_config(bus, sensor):
Conf = bus.read_byte_data(sensor, ACCESS_CONFIG)
TH = decode_DS(bus.read_word_data(sensor, ACCESS_TH))
TL = decode_DS(bus.read_word_data(sensor, ACCESS_TL))
Rpt = '\nStatus of DS1621 at address {}:\n'.format(sensor)
Rpt += '\tConversion is {}\n'.format(
'done' if Conf & DONE else 'in process')
Rpt += '\t{} measured {} degrees Celsius or more\n'.format(
'HAVE' if Conf & TH_BIT else 'have NOT', str(TH))
Rpt += '\t{} measured below {} degrees Celsius\n'.format(
'HAVE' if Conf & TL_BIT else 'have NOT', str(TL))
Rpt += '\tNon-volatile memory is {}\n'.format(
'BUSY' if Conf & NVB else 'not busy')
if Conf & POL_HI:
level, device = 'HIGH', 'cooler'
else:
level, device = 'LOW', 'heater'
Rpt += '\tThermostat output is Active {} (1 turns the {} on)\n'.format(
level, device)
Rpt += '\tDevice is measuring {}\n'.format(
'in One Shot mode' if Conf & ONE_SHOT else 'continuously')
print Rpt
return Conf, TH, TL
My aim is for this to be as usable, readable and understandable as possible.