59

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?

5
  • 3
    Why not raise a ValueError in stead? Aug 16, 2011 at 18:17
  • 17
    If the situation is valid as he states, why would you raise an error?
    – Kimvais
    Aug 16, 2011 at 18:18
  • 5
    It's perfectly valid to stop iterating over a list, yet internally the iterator will raise StopIteration to flag this condition. I find exceptions are not as exceptional as their name would imply in many cases. He could just as well do class NoCityFound(exception): pass Aug 16, 2011 at 18:20
  • 7
    If you return a namedtuple, the users of your functions won't have to unpack the result, and returning None might work as the better choice. Aug 16, 2011 at 18:34
  • 2
    @multipleinterfaces: The difference between ValueError and StopIteration is that the former is, like its name says, an error, while the latter isn't. Aug 17, 2011 at 0:11

9 Answers 9

58

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.

6
  • 14
    +1 I'd probably do a tuple-unpacking assignment (city, state = getTuple(...)) wrapped in a try/catch. This seems to me consistent with python philosophy: try, not test. Also, this way the call site can choose between treating this as an exceptional situation requiring exception or not.
    – liori
    Aug 16, 2011 at 19:38
  • 1
    @liori, relying on exceptions is indeed another nice python idiom, but then I would second @multipleinterfaces' comment: why not raising a ValueError from the function instead of having the caller stumble on a TypeError raised from its own code? Aug 16, 2011 at 20:48
  • Because returning None will break tuple unpacking. Aug 16, 2011 at 22:13
  • 2
    @Ethan, yup, that was the point of my answer. Returning None will raise TypeError from the caller's code if it uses the tuple unpacking idiom, which it might legitimately do if it never encountered an exceptional situation during tests, since the function is supposed to return a tuple in the first place. Even when relying on exceptions for flow control (which is arguably encouraged in Python), in this situation I'd still care about my caller and at least raise the exception from my own code. Aug 16, 2011 at 23:28
  • I'm not a fan of wrapping it in a try/except because, by python standards, it adds a bulky amount of code: 2 lines for try and except, and at least three lines within the except - 1 for checking the type of exception, 1 for passing the exception up, and 1 for the failure state. That's 5 lines for some pretty simple code.
    – speedplane
    Apr 25, 2013 at 4:07
47

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.

2
  • 1
    This is good, not bad. Is it better for them to have to check then for a valid city / state, or to need to wrap that in a try / except?
    – agf
    Sep 16, 2011 at 19:43
  • 3
    How about this? city, state = getCityStateTuple("something") or (None, None)
    – balki
    Aug 21, 2015 at 21:47
12

(None, None) does not evaluate to False in Python. In addition, building a tuple requires more work than, well, not building a tuple. So I would prefer None.

11

As others have noted, a tuple with items in it does not test as False, which is one reason you might want to return None rather than (None, None). However, it is possible to write a tuple subclass that tests as False even when it has items in it by overriding its __nonzero__() method.

class falsetuple(tuple):
    def __nonzero__(self):
        return False

Then you could return falsetuple((None, None)) when there is no value available. In fact, you could always return the same falsetuple.

I'm not necessarily recommending that you do this, in fact I have serious misgivings about flouting this convention, I'm just saying that the truthiness of non-empty tuples is not necessarily in itself a reason to not return a tuple.

6

If your routine normally returns a tuple, then a tuple is what it should keep returning. The real choice is between returning (None, None), or raising an exception, and we don't have enough information to offer good advice on that.

If it were me, and I chose the tuple over the exception, I would go with the FalseTuple that kindall suggests, and also realize that the calling code (which is using tuple unpacking) can also test

if city is None:

to see if a valid result was obtained. This way you are supporting tuple extraction across all possible return values, and still allowing the pythonic idiom of asking the object, "Do you evaluate as True?" (Here is kindall's again for completeness):

class FalseTuple(tuple):
    def __nonzero__(self):
        return False
4

why not making State a property of City? That way your function would return always one value: a City or None.

Returning (None, None) is bad for all the reasons stated in the other answers and serves only to support tuple unpacking.

None is the best value to return to state that no valid city can be returned, but having a function returning 1 or 2 values is not that good, again because of tuple unpacking.

2

To me, returning (None, None) would imply that (None, State) or (City, None) would also be valid return values. If that is the case, go with (None, None), otherwise, Felix and Brent provide very good arguments for simply returning None.

1

I would implement a public method for object that returned, let say isValidLocation() that returns true if location is valid and false if location is none.

1

If you return None, it will be much easier for you to check the return value.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.