if <assignment>:

Duncan Booth duncan at rcp.co.uk
Tue Nov 26 06:04:36 EST 2002


Carl Banks <imbosol at vt.edu> wrote in news:arvjdu$4nk$1 at solaris.cc.vt.edu:

>> If you have more than one or two patterns, then you should really be
>> thinking about a loop rather than a long list of if statements: 
>> 
>> PATTERNS = [
>>  (regex1, action1), (regex2, action2), # ...
>> ]
>> 
>> for regex, action in PATTERNS:
>>    match = regex.match(string)
>>    if match:
>>        action(match)
>>        break
>> 
>> I don't see any need for assignment in an 'if' here.
> 
> Other people often clamor for assignment if here, because the way you
> did is an unnatural and circumlocative way to do something most
> people, myself included, want to do as a sequential piece of code.
> 

Note that I did say 'If you have more than one or two patterns'.
If you do have several patterns, then removing the duplication
seems to me to be a good thing and not at all circumlocutory
(assuming that was the word you meant).
Obviously you wouldn't use a loop in all situations.

If I started off with a piece of code that consisted of a long chain of
if statements, then whether or not it is amenable to refactoring as a
loop, I would certainly want to refactor it as something else: I tend to
the school of thought that likes short methods.

Each to his own though, it would be a boring world if we all wrote
identical code. 



More information about the Python-list mailing list