In python, you can have a function return multiple values. Here’s a contrived example:
def divide(x, y): quotient = x/y remainder = x % y return quotient, remainder (q, r) = divide(22, 7)
This seems very useful, but it looks like it can also be abused (‘Well..function X already computes what we need as an intermediate value. Let’s have X return that value also’).
When should you draw the line and define a different method?
Absolutely (for the example you provided).
Tuples are first class citizens in Python
There is a builtin function
divmod()that does exactly that.There are other examples:
zip,enumerate,dict.items.BTW, parentheses are not necessary most of the time. Citation from Python Library Reference:
Functions should serve single purpose
Therefore they should return a single object. In your case this object is a tuple. Consider tuple as an ad-hoc compound data structure. There are languages where almost every single function returns multiple values (list in Lisp).
Sometimes it is sufficient to return
(x, y)instead ofPoint(x, y).Named tuples
With the introduction of named tuples in Python 2.6 it is preferable in many cases to return named tuples instead of plain tuples.