python - Is it pythonic for a function to return multiple values? -
in python, can have function return multiple values. here's contrived example:
def divide(x, y): quotient = x/y remainder = x % y return quotient, remainder (q, r) = divide(22, 7)
this seems useful, looks can abused ("well..function x computes need intermediate value. let's have x return value also").
when should draw line , define different method?
absolutely (for example provided).
tuples first class citizens in python
there builtin function divmod()
that.
q, r = divmod(x, y) # ((x - x%y)/y, x%y) invariant: div*y + mod == x
there other examples: zip
, enumerate
, dict.items
.
for i, e in enumerate([1, 3, 3]): print "index=%d, element=%s" % (i, e) # reverse keys , values in dictionary d = dict((v, k) k, v in adict.items()) # or d = dict(zip(adict.values(), adict.keys()))
btw, parentheses not necessary of time. citation python library reference:
tuples constructed comma operator (not within square brackets), or without enclosing parentheses, empty tuple must have enclosing parentheses, such a, b, c or (). single item tuple must have trailing comma, such (d,).
functions should serve single purpose
therefore should return single object. in case object tuple. consider tuple ad-hoc compound data structure. there languages every single function returns multiple values (list in lisp).
sometimes sufficient return (x, y)
instead of point(x, y)
.
named tuples
with introduction of named tuples in python 2.6 preferable in many cases return named tuples instead of plain tuples.
>>> import collections >>> point = collections.namedtuple('point', 'x y') >>> x, y = point(0, 1) >>> p = point(x, y) >>> x, y, p (0, 1, point(x=0, y=1)) >>> p.x, p.y, p[0], p[1] (0, 1, 0, 1) >>> in p: ... print(i) ... 0 1
Comments
Post a Comment