How best to write this try/except block?

Rich Harkins rich at worldsinfinite.com
Wed Apr 3 12:12:05 EST 2002


On Wednesday 03 April 2002 12:10 pm, Jeff Youel wrote:
> "Roy Smith" <roy at panix.com> wrote in message
> news:a8fba8$ln8$1 at panix2.panix.com...
>
> > I've got a dictionary d, which may or may not have a value I'm looking
> > for.  If it does, I want to do a few things.  If it doesn't, I want to
> > do a few other things.  I could write:
>
> <snip>
>
> You can avoid the exception handler altogether with:
>
>     value = d.get(key, None)
>     if value:
>         foo = stuff(value)
>     else:
>         foo = otherStuff(key)
>
>
> Jeff

One tweak on this if you want None to be allowed in your dictionary then do 
something like the following:

def fn(d):
	MYBLANKVALUE='MYBLANKVALUE'
	obj=d.get(key,MYBLANKVALUE)
	if obj is MYBLANKVALUE:
		# Do something positive with obj
	else:
		# Do something else...

Because of the is comparison even if "MYBLANKVALUE" is in d then this code 
will still work.  Just don't intern whatever "MYBLANKVALUE" is (I frequently 
use undefined="UNDEFINED").

Rich





More information about the Python-list mailing list