if does not evaluate
Robert Brewer
fumanchu at amor.org
Sat Jun 5 12:06:33 EDT 2004
Jim Newton wrote:
> A question that has bothered me ever since looking at python
> the first time is that not everything evaluates to something.
Are you only bothered by it because there's no ifelse operator? ;)
> I am wondering what is the reason for this. Would making
> everying evaluate have caused the langugage to be less
> efficient execution-wise? or was it a choice to enforce some
> sort of standard?
Only Zen standards:
1. Beautiful is better than ugly.
2. Explicit is better than implicit.
3. Simple is better than complex.
6. Sparse is better than dense.
7. Readability counts.
> I've read a few discussions about the fact that there is
> no if/then/else operartor.
>
> Wouldn't this problem be easily solved by making the built
> in keywords actually be evaluatable.
>
> I.e., x = if something:
> expr1
> else:
> expr2
>
> parentheses would of course be optional as they are for
> all expressions.
You'll first have to convince many people that this is a "problem" to be
"solved". Why is your solution "better than":
if something:
x = expr1
else:
x = expr2
Then you need to show why the alternatives aren't good enough:
If your main desire is to code in some other language while still using
Python, write your own VB-style IIf function:
>>> def IIf(expression, truepart, falsepart):
... if expression:
... return truepart
... return falsepart
...
>>> x = IIf('something', 'expr1', 'expr2')
>>> x
'expr1'
If your main desire is to provide a one-liner, use a tuple (which is
still ugly):
>>> x = ('expr2', 'expr1')[bool('something')]
>>> x
'expr1'
Or a mapping (which is prettier, but still uglier than the regular if:
else:
>>> x = {True: 'expr1',
... False: 'expr2'}[bool('something')]
>>> x
'expr1'
Or a more generic morphing function:
>>> def surjection(input, mappings):
... mappings = dict(mappings)
... return mappings[input]
...
>>> x = surjection(bool('something'), {True: 'expr1', False: 'expr2'})
>>> x
'expr1'
>>> x = surjection(bool('something'), [(True, 'expr1'), (False,
'expr2')])
>>> x
'expr1'
>>> x = surjection('something', [('something', 'expr1'), ('other',
'expr2'), ('than', 'expr2')])
>>> x
'expr1'
Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org
More information about the Python-list
mailing list