[Python-3000] Exception Expressions

Michael Chermside mcherm at mcherm.com
Fri Sep 1 17:03:59 CEST 2006


Calvin Spealman writes:
> I thought I felt in the mood for some abuse today, so I'm proposing
> something sure to give me plenty of crap, but maybe someone will enjoy
> the idea, anyway.
        [...]
>     expr1 except expr2 if exc_type

This is wonderful!

In combination with conditional expressions, list comprehensions, and
lambda, I think this would make it possible to write full-powerd Python
programs on a single line. Actually, putting it on a single line in your
text editor would just make things unreadable, but if you wrap
parentheses around it, then the entire program can be a single
expression, something like this:

     for entry in entryList:
         if entry.status() == 'open':
             try:
                 entry.display()
             except DisplayError:
                 entry.setStatus('error')
                 entry.hide()
         else:
             entry.hide();

would become this:

     (   (   (   entry.display()
                 except (
                     entry.setStatus('error'),
                     entry.hide()
                 )
                 if DisplayError
             )
             if entry.status() == 'open'
             else entry.hide()
         )
         for entry in entryList
     )

(Or you *could* choose to compress it as follows:)

     (((entry.display()except(entry.setStatus('error'
     ),entry.hide())if DisplayError)if entry.status()
     =='open' else entry.hide())for entry in entryList)

Now, I wouldn't try to claim that this single-expression
version is *more* readable than the original, but it
has a significant advantage: it makes the language no
longer dependent on significant whitespace for demarking
lines and blocks! There are places where significant
whitespace is a problem, most notably when trying to
embed Python code within other documents.

Just imagine using this new form to embed Python
within HTML to create a new and more powerful form of
dynamic page generation:

    <div class="entrydiv">
       <p class="item-title"><*entry.title()*></p>
       <ul>
          <* "<li>Valid</li>" if entry.isvalid() else "" *>
          <* "<li>Active</li>" if entry.active else "<li>Inactive</li>" *>
       </ul>
       <p class="item-content">
          <* entry.showContent() except "No Data Available" if Exception *>
       </p>
    </div>

Isn't it amazing?

.
.
.

Okay... *everything* above comes with a HUGE wink. It's
a joke. Calvin's idea is clever, and readable once you get
used to conditional expressions, but I'm still a solid -1
on the proposal. But thanks for giving me something fun to
think about.

-- Michael Chermside



More information about the Python-3000 mailing list