Conditional operator in Python?

Cezary Biernacki cezary at bigfoot.com
Tue Sep 4 06:17:52 EDT 2001


Fredrik Lundh wrote:
> Weet Vanniks wrote:
>>def cond_choose(cond,first_choice,second_choice):
>>     if cond:
>>          return first_choice
>>     return second_choice
> well, compare
> 
> whatever = cond_choose(cond, format_disk(), leave_it_as_is())

My proposition:
def cond_choose( cond, when_true, when_false, *args ):
	if cond:
		return when_true( *args )
	else:
		return when_false( *args )

E.g.:
whatever = cond_choose( cond, format_disk, leave_is_as_is )

factorial = lambda x : cond_choose( x == 1,\
                     lambda x : 1L, \
                     lambda x : factorial( x - 1 ) * x, x )

division_test = lambda x, y: cond_choose( y == 0:\
                     lambda x, y : 0, \
                     lambda x, y : x/y, x, y )

---
Cezary




More information about the Python-list mailing list