[Tutor] Should error checking be duplicated for both functions if one function calls another one?

Peter Otten __peter__ at web.de
Mon Jun 1 17:30:15 CEST 2015


boB Stepp wrote:

> On Mon, Jun 1, 2015 at 9:33 AM, David Palao <dpalao.python at gmail.com>
> wrote:
>> Hello,
>> Not sure if I got it, but, in my opinion functions should do only one
>> thing.So if function 2 finds an error, it should raise it. There
>> should be another function  (function 1 in your case?) taking care of
>> possible raised errors.
> 
> I guess my question was not clearly worded. The idea is that function
> 1 calls another function. Function 1 checks for possible errors that
> are relevant. Some or all of these checks are also relevant to the
> called function. Should the called function also include these
> relevant error checks?

I think more important than not repeating the checks is that you avoid 
duplicate code that does the same thing. If the checks are relatively cheap 
I don't see a problem with

def check(a):
    """Verify that a ...

    Helper for f1() and f2().
    """
    if ...:
        raise ValueError

def f1(a, b):
    check(a)
    c = ...
    f2(a, c)

def f2(a, c):
    check(a)
    ... # actual work

Alternatively you can make f2() private by convention:

def f1(a, b):
   check(a)
   c = ...
   _f2(a, c)


def _f2(a, c):
    """Frobnicate a with c.

    Should only be called by f1() which first verifies that
    `a` cannot explode.
    """
    ...

Should you need a standalone version of f2() later just implement it as

def f2(a, c):
    check(a)
    return _f2(a, c)






More information about the Tutor mailing list