[Tutor] functions: use return or exceptions?

Steven D'Aprano steve at pearwood.info
Fri Sep 24 02:54:01 CEST 2010

On Fri, 24 Sep 2010 06:06:25 am Luke Paireepinart wrote:
> You should do both. Raise an exception in the exceptional case.
> My general pattern is to return None if no results exist, return the
> results if they do exist, and raise an exception if I couldn't
> perform the function.

I hate that! I find that idiom, as used by the re module, to be the 
worst of all possible worlds.

To do something with a search result, you have to:

be prepared for an exception (either catch it, or let it bubble up the 
call chain);

if you get a result, you have to compare it to None and be prepared to 
ignore it;

if the result isn't None, then you can do something with it. This itself 
may include further tests or catching exceptions.

At the interactive interpreter, you can't write (say):


because the result is sometimes None. So you have to split it into two 

mo = regex.search(text)
if mo: mo.group()

That's a nuisance when working interactively. I would prefer it if the 
re search functions returned a "blank" match object, so you could say:

re.search('sp.m', 'I like spam and eggs').group(0)
=> prints 'spam'

re.search('sp.m', 'I like ham and eggs').group(0)
=> prints ''

> Eg. If I have a function that creates a list of users with a first
> name of bob, I'll return the users or None (or probably an empty
> list) 

Returning an empty list makes sense. Returning None makes no sense at 

> but if the db connection is unsuccessful I'll let the exception 
> it throws propagate back up from my function, or possibly trap and
> rethrow the exception.

That's okay.

> Or if a db connection error shouldn't matter to the calling function,
> I just won't re raise the exception.

That's a reasonable approach as well.

Steven D'Aprano

More information about the Tutor mailing list