More efficient/elegant branching

DL Neil PythonList at DancesWithMice.info
Sun Dec 22 14:35:50 EST 2019


On 11/12/19 1:07 AM, Daniel Haude wrote:
> Hello Neil,
> thanks for the detailed answer.
> 
>> Question: are there other people/factors who/which should be regarded
>> as more important than the linter's opinion?
> Yes. Mine.

Um, see below...
(unless humor)


> I was just puzzled at the linter's output (took me a while to figure out 
> what it actually meant), and that got me started on the track if there 
> was maybe a more Pythonic way of dealing with that decision chain.
...

>> One reason why this code looks a bit strange (and possibly why PyLint
>> reacts?) is because it is trivial. When we look at the overall
>> picture, the question becomes: what will the 'mainline' do with
>> "result" (the returned value)? Immediately one suspects it will be fed
>> into another decision, eg:
> 
> No, the "result" is a text message that actually means something and is 
> eventually output for human consumption.
> 
> The whole thing is rather academic. Also my efficiency argument doesn't 
> hold water because this routine is executed just a few times per hour. I 
> like the "condition table" approach for its lower line count but I'll 
> stick with if/elif because it's more conventional and therefore easier 
> to understand for the casual reader.

+1 (except that it's your future-self or another maintainer who is 
important rather than anyone 'casual')


A reason we are having difficulty making suggestions is because the 
example has been abstracted. Thus we had no idea that the objective was 
to (possibly) output to SMS, nor more importantly, the meanings of a, b, 
and z. (it's all algebra to me!)

In some/another application you may like to consider constructing the 
source-data for this decision within a class. Then the conditions can 
become methods or even properties of the class - remembering that a 
property could be some combination of attributes, eg a > 4 and b == 0. 
Alternatively, the class could maintain some idea of 'status', where 
"first" corresponds to the preceding 'state', "second" when len(z) falls 
below 2, etc. The class's property/ies thus simplify the 
SMS-transmission process/class...

Appropriate name-choices will make the code self-documenting - per the 
'reading' objective:

	if employee.worked_overtime:
		sms.send( "We're in the money...!" )

-- 
Regards =dn


More information about the Python-list mailing list