For review: PEP 308 - If-then-else expression

Carlos Ribeiro cribeiro at
Sun Feb 9 00:58:34 CET 2003

On Saturday 08 February 2003 03:00 pm, holger krekel wrote:
> IMO Laura emphasized how good enforcing indentation is for
> readability.  Writing 'x and y or z' or 'x if y else z'
> (or list-comps for that matteR) undermines readability.

In some cases, too many indentation levels can be a problem. The type of code 
that I write most of the time - scripts to filter and prepare analytical 
reports based on relational data - is full of simple tests that can be 
conveniently written as conditional expressions (Things like substituting a 
null value with zeros, or fixing fields that were left unassigned in the 
original database). By doing this, the program structure would be much 
cleaner, without four line 'if' blocks that are not part of the program 
logic, but are there to do simple translations and adjustments on the data 
being processed.

> I think what *could* be more useful is something like
>     <expression1> except <error>: <expression2>
> which enhances Python's philosophy of not requiring
> Look-before-you-leap.  Hopefully it's obvious what
> this does and IMO it reads comparatively well because
> you don't have three entities (one condition and two expressions)
> to parse.  With it you can substitute stuff like
>     try:
>         result = something.method()
>     except AttributeError:
>         result = None
> with
>     result = something.method() except AttributeError: None
> which reads from left to right.  Maybe i just have been
> working too much with exceptions, lately :-)

You hit a chord, here - that's would be a good substitute for almost all of my 
usages of a conditional operator. Real databases aren't perfect; it is common 
to have a few records with missing or invalid fields that have to be 
effectively filtered or ammended when processing the data. Of course, it is 
much better to validate the data on input, but there is a limit on what you 
can do in practice; for example, too much validation may turn a system 
unusable, because missing data is sometimes a fact of life. And even you try 
to enforce it, people always find a way around, but that's another matter 
entirely. In the end you have to deal with all these exceptions when building 
analytical reports, and your proposal comes perfect in this situation.

Carlos Ribeiro
cribeiro at

More information about the Python-list mailing list