Python Exception Handling – Inform Caller or Let Them Deal with Exception?

exception handlingexceptionsparameterspython

I'm not sure how to proceed in the following situation.

say we have a function as so:

def runsATask(codes):
    myDicts = [helperFunc(code) for code in codes]
    for item in myDicts:
        # some logic.

Here's the problem, codes is some iterable and should be either a list or a tuple, ie it should be used as so: runsATask(['code1', 'code2', ... 'codeN']), but sometimes N is 1 and so people could call it mistakenly, like so, runsATask('code1') This code will still run, but later on in the for loop it will crap out because myDicts doesn't have the correct objects in it because the list comprehension that made it iterated over a string rather than a list/tuple.

So should I leave it as it is or would the following be a solution:

def runsATask(codes):
    if not isinstance(codes, (list, tuple)):
        raise Exception("Codes should be a list or a tuple")
    myDicts = [helperFunc(code) for code in codes]
    for item in myDicts:
        # some logic.

I'm not sure which way to go because I hear Python circles say to let callers deal with the issue, but debugging a situation like this can be annoying because the caller would deal with the issue in the for loop and had he been informed way earlier about the wrong parameter being passed, then it would save a lot of wasted time.

Best Answer

This code

if not isinstance(codes, (list, tuple)):
    raise Exception("Codes should be a list or a tuple")

Is called a Guard Clause, and it's a perfectly valid technique.

The reason you throw an exception here is that (presumably), if codes is not an instance of (list, tuple), then the method has no way to recover (unless you want to return some default value or error code from the method instead).