APR
15
2005

Trinary operator in python

Here's an example of an easy and compact way to simuate the trinary operator in python. It is not short circuit like the one in C, but it is pretty simple:

  newowner    = [self.newowner, None][self.contactid == self.newowner]

This will set newowner to self.newowner if self.contactid is not the same as self.newowner. Otherwise it will set it to None.
[EDIT] How the hell do I stop drupal destroying square brackets?
[EDIT] Aha, you need to use escape codes.

Comments

this is why i don't really like python very much. so much of its syntax looks like RPN C to me and you end up doing odd things like this to emulate the features one wants ;)

btw, i've always called it the ternary operator. according to google this is the more popular name for it. i wonder if this is regional?


By Aaron J. Seigo at Fri, 04/15/2005 - 19:10

Not sure, I've always called it the trinary operator.


By Richard Moore at Sat, 04/16/2005 - 10:47

What about following function used for ages with spreadsheets, functional languages, and so on:


def iif(test, iftrue, iffalse):
if test:
return iftrue
else:
return iffalse

define that once and then just:


newowner = iif(self.contactid == self.newowner,
self.newowner, None)

BTW, I am from Poland, so I may like RPN, however I consider Richard's solution as an 'obfuscated code' trick. And, the fact that Python like any other tool allows for doing tricks, proves me nothing :)


By Jarosław Staniek at Sat, 04/16/2005 - 19:06

The ternary operator in ruby is just like the C one:
newowner = (contactid == newowner ? newowner : nil)


By Richard Dale at Sun, 04/17/2005 - 00:20