Python ternary operation
Filed under Python, hacks on jul 22, 2010
Python has no ternary operation, or has it? At least not directly, we had a discussion about possible solutions in the #python IRC channel on FreeNode and after some filddling I came up with this hack abusing the Python slicing magic:
class Ternary(object):
'''
Ternary-ish emulation, it looks like C-style ternary operation::
x = a ? b : c
In Python we would write::
>>> x = a and b or c
Or (rather than above, this is safe for returning Falsy values for b)::
>>> x = (a and [b] or [c])[0]
Or::
>>> x = b if a else c
Or::
>>> x = lambda i: (b, c)[not a]
Or::
>>> if a:
... x = b
... else:
... x = c
Now we can also write::
>>> x = ternary[a:b:c]
'''
__getitem__ = lambda s, sl: (sl.start and sl.stop, not sl.start and sl.step)[not sl.start]
# Actual "operation", we can only work with an instance
T = Ternary()
This would produce:
>>> from ternary import ternary >>> print ternary[0:2:3] 3 >>> print ternary[1:2:3] 2 >>> s = '' >>> print ternary[s:s.split():None] None >>> s = 'hello world' >>> print ternary[s:s.split():None] ['hello', 'world'] >>>
This package has been released on PyPI as ternary.
Post your feedback
You can use this form to leave your feedback. Your insights are always appreciated.