[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.python

Re: Re Interest check in some delicious syntactic sugar for "except:pass"

Tim Chase

3/3/2010 2:49:00 PM

Oren Elrad wrote:
> """ code involving somefile """
> try:
> ........os.remove(somefile)
> except:
> .......pass # The bloody search indexer has got the file and I
> can't delete it. Nothing to be done.


I admit there are times I've done something similar, usually with
what I call my "int0" and "float0" utility functions which
roughly translate to "give me a stinkin' int/float and if
something goes wrong, give me 0, but the return result better
darn well be an int/float!" functions. But as you describe and
was later commended as a right-ish way to approach it,
abstracting that off into a function with minimal code in the
try: block is the right way to go.

-tkc


def int0(v):
"""converts v to a int, or returns 0 if it can't"""
try:
return int(v)
except: # usually a ValueError but catch all cases
try:
# int("1.1") fails so try float()ing it first
return int(round(float(v)))
except:
return 0

def float0(v):
"""converts v to a float, or returns 0 if it can't"""
try:
return float(v)
except:
return 0.0




1 Answer

Mel

3/3/2010 3:43:00 PM

0

Tim Chase wrote:
> I admit there are times I've done something similar, usually with
> what I call my "int0" and "float0" utility functions which
> roughly translate to "give me a stinkin' int/float and if
> something goes wrong, give me 0, but the return result better
> darn well be an int/float!" functions. But as you describe and
> was later commended as a right-ish way to approach it,
> abstracting that off into a function with minimal code in the
> try: block is the right way to go.
[ ... ]

> def int0(v):
> """converts v to a int, or returns 0 if it can't"""
> try:
> return int(v)
> except: # usually a ValueError but catch all cases
> try:
> # int("1.1") fails so try float()ing it first
> return int(round(float(v)))
> except:
> return 0
>
> def float0(v):
> """converts v to a float, or returns 0 if it can't"""
> try:
> return float(v)
> except:
> return 0.0

I think replacing `except:` with `except StandardError:` would work as well,
and be correct, too.

Mel.