Trigraph Idiom - Original?

Shane Hathaway shane at hathawaymix.org
Wed Apr 27 21:42:28 EDT 2005


Jeff Winkler wrote:
> I've come up with a trigraph idiom, am curious if it's been done before
> (probably). I like to use trigraphs occasionally.
> 
> Scenario: I'm doing an RSS->Javascript conversion for our intranet. I'd
> like to use different CSS class if a post is new. Code:
> 
> hoursOld=abs(time.time()-time.mktime(i.modified_parsed))/3600
> cssClass=['rssLink','rssLinkNew'][hoursOld<12]
> entry='<a href="%s" class="%s" target="detail">%s</a>' %
> (cssClass,i['link'],i['title'])
> 
> So, ['rssLink','rssLinkNew'] is index by boolean value- False:0, or
> True:1.
> 
> I realize many will find this hideous, but 3 lines of code to do
> something simple seems equally bad. Thoughts? Is there a better way?

The need for ternary expressions seems to center around presentation to
humans.  I find myself using such expressions frequently in presentation
templates or in code that prepares information for templates.  You're
using it the same way.

I always write it this way:

    condition and truecase or falsecase

This works as long as truecase evaluates as a true value.  (If it
doesn't, the result of the expression is falsecase.)  So I would write
the cssClass assignment like this:

    cssClass = (hoursOld < 12) and 'rssLinkNew' or 'rssLink'

The C equivalent is more readable, but this is close enough.  It's the
same trick people use in shell scripts.

Shane



More information about the Python-list mailing list