This is an old copy of the Python FAQ. The information here may be outdated.

How do I write a function with output parameters (call by reference)?

Python doesn’t support call by reference; a called function only has access to the argument values (the actual objects), not the variables in the calling scope.

To return multiple values, you can simply return a tuple, and use sequence unpacking at the call site:

def func(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 = func(x, y)
print x, y                 # output: new-value 100

This is almost always the clearest solution, but can cause problems if you find that need to add more return values.

A more flexible approach is to return either a dictionary or a custom class instance. Dictionaries are easy to create, but can be a bit unwieldy to unpack:

def func(a, b):
    return dict(a='new-value', b=b+1)

result = func(x, y)
print result["a"], result["b"]

Custom classes require a bit more typing, but are easier to use at the call site:

class result_container:
    pass

def func(a, b):
    result = result_container()
    result.a = 'new-value'
    result.b = b + 1
return result

result = func(x, y)
print result.a, result.b

Extending the container class to support dictionary-style creation is also easy:

 
class result_container:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs) # copy arguments to attributes

def func(a, b):
    return result_container(a='new-value', b=b+1)

result = func(x, y)
print result.a, result.b

Finally, you can return multiple values from a function by passing in a mutable object, such as a list, a dictionary, or a custom object. This example uses a list:

def func(a):
    a[0] = 'new-value'     # 'a' references a mutable list
    a[1] = a[1] + 1        # changes a shared object

args = ['old-value', 99]
func(args)
print args[0], args[1]     # output: new-value 100

And this uses a dictionary:

 
def func(args):
    args['a'] = 'new-value'     # args is a mutable dictionary
    args['b'] = args['b'] + 1   # change it in-place

args = {'a':' old-value', 'b': 99}
func(args)
print args['a'], args['b']

CATEGORY: programming

 

A Django site. rendered by a django application. hosted by webfaction.