From 5af79a80004b260826ddb118698c7be4fde079bf Mon Sep 17 00:00:00 2001 From: wirawan Date: Fri, 22 Jan 2010 18:46:50 +0000 Subject: [PATCH] * Syntactic sugars for quick-and-dirty python programming. --- sugar.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 sugar.py diff --git a/sugar.py b/sugar.py new file mode 100644 index 0000000..2b151df --- /dev/null +++ b/sugar.py @@ -0,0 +1,31 @@ +#!/usr/bin/ipython -pylab +# +# $Id: sugar.py,v 1.1 2010-01-22 18:46:50 wirawan Exp $ +# +# Created: 20100121 +# Wirawan Purwanto +# +# Syntactic sugar for python programming. May not be efficient, but many +# of these tools are nice for quick-and-dirty programming. +# Beware of their caveats! +# +# + +def ifelse(cond, trueval, *args): + """An alternative to python's own ternary operator, but with multiple + conditions to test (like chained if-else-if-else... which is found in + e.g. m4 language). + This is of course only a syntactic sugar with its inefficiency and + dangers (all expressions are evaluated before choosing which one is to + select). So, beware!""" + if cond: + return trueval + else: + i = 0 + while i+1 < len(args): + if args[i]: return args[i+1] + i += 2 + + if i < len(args): return args[i] + + return None # Fallback solution: "None"