[Tutor] Pattern to handle exceptions

Kent Johnson kent37 at tds.net
Sat Sep 24 05:20:21 CEST 2005


Negroup - wrote:
> Hi all, I have a question about the following lines of code:
> 
> 
>>>>class Foo:
> 
> ...     bar = 'bar'
> ...
> 
>>>># is it better this
>>>>def te(attribute):
> 
> ...     try:
> ...             print getattr(c, attribute)
> ...     except AttributeError:
> ...             return None
> 
>>>>#
>>>># or this?
>>>>def h_a(attribute):
> 
> ...     if hasattr(c, attribute):
> ...             return getattr(c, attribute)
> ...     else:
> ...             return None
> ...
> 
> Generally, to handle potentially erroneus situations, which pattern is
> most correct to use?

In the Python world, the first style is known as Easier to Ask Forgiveness than Permission (EAFP), the second style is Look Before You Leap (LBYL). In general EAFP is preferred - the idea is, if you want to know whether an object can do what you want, you just try it and if it doesn't work then clean up. It's not always that simple, for example if you want to do several operations and it would be messy to clean up if the last one failed, you may use LBYL. But the preference is for EAFP.

In this particular case, I would use the default argument form of getattr() and write it as
def da(attribute):
  return getattr(c, attribute, None)

Kent



More information about the Tutor mailing list