Search code examples
pythonpython-2.5ternary

Best way to do ternary conditionals in Python < 2.5


I have to bear with a Python version < 2.5 (it is 2.4.3 for specifics)

It seems that ternary operators were introduces in Python starting at 2.5. For those who are not familiar, ternary operators in Python >= 2.5 look like this:

def do_ternary(flag):
    return "foo" if flag else "bar"

I'd like to know some solutions to emulate this in the early versions of Python. I can for sure do it with if ... else, but I'm looking for something more pythonic that I wouldn't be ashamed to put on some production-level code :)

Thanks for the help !


Solution

  • Actually I was looking on the web and found what seems like a really elegant pythonic solution:

    def _if(test):
        return lambda alternative: \
                   lambda result: \
                       [delay(result), delay(alternative)][not not test]()
    
    def delay(f):
        if callable(f): return f
        else: return lambda: f
    
    >>> fact = lambda n: _if (n <= 1) (1) (lambda: n * fact(n-1))
    >>> fact(100)
    93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000L
    

    What do you think about this one? It looks pretty clean and easy to read in my opinion.