Should I Return None or (None, None)?

We have a object method that returns a city/state tuple, i.e. ('Boston', 'MA'). Under some valid circumstances, there is no valid city/state to return. Stylistically, does it make more sense to return None, or a two element tuple containing (None, None) in that case?


I would return None. If there is no result, why return something that looks like a result?

It is also easier to test:

result = getCity()
if result:
   # do something

I would only return (None, None) if it were possible that only one of the two values is None (i.e. ('Boston', None)). It would be more consistent in this case.


By only returning one value in exceptional circumstances, you risk breaking the tuple unpacking idiom. Some of your callers might issue:

city, state = getCityStateTuple("something")

In that case, returning None will break the caller with the error:

TypeError: 'NoneType' object is not iterable

So, I personally would return (None, None) in your situation. Then again, your mileage may vary, and it depends on the pattern used by your callers.