[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

what's this instance?

J. Peng

1/22/2008 7:37:00 AM

def safe_float(object):
try:
retval = float(object)
except (ValueError, TypeError), oops:
retval = str(oops)
return retval

x=safe_float([1,2,3,4])
print x


The code above works well.But what's the instance of "oops"? where is it
coming from? I'm totally confused on it.thanks.
4 Answers

Marc 'BlackJack' Rintsch

1/22/2008 8:08:00 AM

0

On Tue, 22 Jan 2008 15:36:49 +0800, J. Peng wrote:

> def safe_float(object):
> try:
> retval = float(object)
> except (ValueError, TypeError), oops:
> retval = str(oops)
> return retval
>
> x=safe_float([1,2,3,4])
> print x
>
>
> The code above works well.But what's the instance of "oops"? where is it
> coming from? I'm totally confused on it.thanks.

`oops` is bound to the `ValueError` or `TypError` object if `float()`
raises such an exception.

Ciao,
Marc 'BlackJack' Rintsch

Bruno Desthuilliers

1/22/2008 9:12:00 AM

0

J. Peng a ¨|crit :
> def safe_float(object):
> try:
> retval = float(object)
> except (ValueError, TypeError), oops:
> retval = str(oops)
> return retval

> The code above works well.

For which definition of "works well" ?

This function is really ill-named - it returns either a float or a
string, so it is definitively not safe :

def dosomething(x):
return x + (x / 0.5)

x=safe_float([1,2,3,4])
// a dozen line of code here
y = dosomething(x)

And now, have fun trying to trace the real problem... Better to not use
this function at all IMHO - at least, you'll get a meaningfull traceback.

> But what's the instance of "oops"? where is it
> coming from? I'm totally confused on it.thanks.

cf other answers on this.

J. Peng

1/22/2008 9:26:00 AM

0

Bruno Desthuilliers D'µà:
> J. Peng a ¨|crit :
>> def safe_float(object):
>> try:
>> retval = float(object)
>> except (ValueError, TypeError), oops:
>> retval = str(oops)
>> return retval
>
>> The code above works well.
>
> For which definition of "works well" ?
>

I got it from Core Python Programming book I bought.You may ask it to
Westley Chun.:)

Bruno Desthuilliers

1/22/2008 11:48:00 AM

0

J. Peng a ¨|crit :
> Bruno Desthuilliers D'µà:
>> J. Peng a ¨|crit :
>>> def safe_float(object):
>>> try:
>>> retval = float(object)
>>> except (ValueError, TypeError), oops:
>>> retval = str(oops)
>>> return retval
>>> The code above works well.
>> For which definition of "works well" ?
>>
>
> I got it from Core Python Programming book I bought.You may ask it to
> Westley Chun.:)

Ok: Mr Chun, if you here us ?-)