}

How to pass a variable as reference in python

Created:

Introduction

When you call a function or method there are two was to pass the argument:

  • By value: The caller and the callee have two different objects and changes inside the function will not be reflected on the caller scope.
  • By reference: The caller and the calee use the same variable and changes inside the called function will impact outside.

In python all arguments are passed by assigment (see python docs here). This means that the assiment will create new references to objects, the reference is always passed as value. Note that there is no a call by reference in python, but you can mimick (see examples above) call by reference since the object can be modified (it's a reference). There is a special case with immutable objects, those are always passed by value.

To see the grey line between references passed by value and call by reference, check this code:

def test1(param):
    param['a'] = 1

def test2(param):
    param = None

def test_inmutable(inmutable):
    inmutable = inmutable + 'a'

mutable_obj = {}

test1(mutable_obj)
print(mutable_obj)
# you will see {'a': 1}
test2(mutable_obj)
print(mutable_obj)
# you will see {'a': 1} and not None.

inmutable_obj = 'test string'
test_inmutable(inmutable_obj)

print(inmutable_obj)
# you will see 'test string' as the original assigment