Tweeted twitter.com/#!/StackProgrammer/status/426930310513979392
3 edited tags
| link
2 Don't need tag in title.
| link

Inform caller or just let them deal with exception? Python

1
source | link

Inform caller or just let them deal with exception? Python

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.