Why would I get a TypeEror?

Reinhold Birkenfeld reinhold-birkenfeld-nospam at wolke7.net
Fri Jan 14 23:06:43 CET 2005


Steven Bethard wrote:
> It's me wrote:
>> Say again???
> 
> Please stop top-posting -- it makes it hard to reply in context.
> 
>> "Reinhold Birkenfeld" wrote...
>>>It's me wrote:
>>>>If this is true, I would run into trouble real quick if I do a:
>>>>
>>>>(1/x,1.0e99)[x==0]
>>>
>>>Lazy evaluation: use the (x==0 and 1e99 or 1/x) form!
> 
> If you want short-circuting behavior, where only one of the two branches 
> gets executed, you should use Python's short-circuiting boolean 
> operators.  For example,
> 
>      (x == 0 and 1.0e99 or 1/x)
> 
> says something like:
> 
>      Check if x == 0.
>      If so, check if 1.0e99 is non-zero.  It is, so return it.
>      If x != 0, see if 1/x is non-zero.  It is, so return it.
> 
> Note that if you're not comfortable with short-circuiting behavior, you 
> can also code this using lazy evaluation:
> 
>      (lambda: 1/x, lambda: 1.0e99)[x==0]()

Or even

(x==0 and lambda: 1e99 or lambda: 1/x)()

Or ...


Reinhold



More information about the Python-list mailing list