Good code patterns in Python
Max M
maxm at mxm.dk
Wed Jul 2 02:28:28 EDT 2003
Michael Chermside wrote:
> Will Stuyvesant writes:
>
>>If you know that your source code is going to be used
>>later by others, then I feel that code with the pattern:
>>
>> if some_condition:
>> some_name = some_value
>> else:
>> some_name = other_value
>>
>>is often a mistake. Much better, safer, would be:
>>
>> some_name = some_value
>> if not some_condition:
>> some_name = other_value
>
> I disagree with you... I think that the first form is superior
> to the second. Here are two reasons.
>
> My number one reason is readability. Seeing "some_name = some_value"
> when some_name is ACTUALLY going to take on other_value is very
> misleading to the reader.
If a programmer has a hard time reading the first version, he really
should have another job ;-)
You cannot expect to know from any program what value a variable has
from a cursory glance.
And there are many times where it is the prefered idiom. Like:
result = []
if something:
result.append(stuff)
if something_else:
result.append(stuff)
return result
Another example:
url = self.url
http = 'http://'
if url[:len(http) != http
url = http + url
return url
The "first" form is not an unusual pattern to see in programmes. And I
prefer it myself, as it prevents small stupid mistakes better than the
"second" form.
The first form frequently mutates into nested code like:
if some_condition:
some_name = some_value
else:
if some_exotic_condition:
some_name = other_value
Where it can be pretty obscure what value a variable has, and if it is
assigned one at all.
And you have to make shure to set the "default" value in all itterations
of the code.
if some_condition:
some_name = some_value
else:
if some_exotic_condition:
some_name = third_value
else:
some_name = other_value
It would have been a simpler and less error prone procedure to change
the code if it it had used the first form.
some_name = other_value
if some_condition:
some_name = some_value
else:
if some_exotic_condition:
some_name = third_value
regards Max M
More information about the Python-list
mailing list