Re: Good code patterns in Python
by Terry Reedy other posts by this author
Jul 1 2003 4:31PM messages near this date
Re: Good code patterns in Python
|
Re: Good code patterns in Python
"Will Stuyvesant" <hwlgw@[...].com> wrote in message
news:cb035744.0307010149.399df2eb@[...]..
> 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
If, bool(some_value) == True, I personally would use the near-ternary
idiom
some_name = some_condition and some_value or other_value
(or equivalent form for bool(other_value)== True or either == False).
This is both safe and efficient, avoiding both
> Because those people reusing your code might decide to
> change or adapt the "if" part of the first example. Or
> the "else" part for that matter. And then they could end
> up with "some_name" being undefined, crashing other code
> maybe 1000's of lines away.
and
> There is the small overhead of assigning something twice
(I acknowledge that some think this ugly and worse and would not be
caught dead writing such an 'abomination', so flame repetition is not
necessary ;-)
Terry J. Reedy
--
http://mail.python.org/mailman/listinfo/python-list
Thread:
Will Stuyvesant
Ben Finney
Erik Max Francis
Bernhard Herzog
holger krekel
Kirk Job-Sluder
Erik Max Francis
Dennis Lee Bieber
Jiri Barton
Lulu of the Lotus-Eaters
Terry Reedy
Steven Taschuk
Michele Simionato
|