Good code patterns in Python
Erik Max Francis
max at alcyone.com
Wed Jul 2 03:12:48 EDT 2003
Kirk Job-Sluder wrote:
> Will Stuyvesant <hwlgw at hotmail.com> wrote:
>
> > 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
> >
> > Why?
>
> My personal opinion is that it depends on context. The first idiom
> is more clear when you are dealing with some kind of a switch. The
> second idiom works better if you have a default value that needs to be
> overridden in some cases.
I presume the "mistake" he's referring to with the first snippet is the
potential problem that could happen if the variable is named
incorrectly:
if condition:
variable = someValue
else:
varaible = otherValue # [sic] note the typo!
When you really want an atomic assignment of one singular variable. The
complete solution to this would probably be a conditional expression,
e.g.:
variable = (if condition: someValue else: otherValue)
eliminating the duplication which can lead to errors. (Python, of
course, doesn't have such a construct, and the silence after the
conditional expression PEP vote and the long silence thereafter suggests
that it never will.)
I still don't think this significant of a risk to warrant widespread
conversion of statements to the form Will suggests, especially when you
have things like PyChecker that can check for (probable) typos. It's a
slightly unfortunate wart in dynamic languages without conditional
operators, but I don't think it rises to the level of something that
should be corrected via such (what seems to me) a heavy-handed style.
--
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
__ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/ \ When the solution is simple, God is answering.
\__/ Albert Einstein
More information about the Python-list
mailing list