How do I write a function with output parameters (call by reference)?
Remember that arguments are passed by assignment in Python. Since assignment just creates references to objects, there’s no alias between an argument name in the caller and callee, and so no call-by-reference per se. You can achieve the desired effect in a number of ways. • By returning a tuple of the results: def func2(a, b): a = ‘new-value’ # a and b are local names b = b + 1 # assigned to new objects return a, b # return new values x, y = ‘old-value’, 99 x, y = func2(x, y) print x, y # output: new-value 100 This is almost always the clearest solution. • By using global variables. This isn’t thread-safe, and is not recommended. • By passing a mutable (changeable in-place) object: def func1(a): a[0] = ‘new-value’ # ‘a’ references a mutable list a[1] = a[1] + 1 # changes a shared object args = [‘old-value’, 99] func1(args) print args[0], args[1] # output: new-value 100 • By passing in a dictionary that gets mutated: def func3(args): args[‘a’] = ‘new-value’ # args is a mutable dictionar