Mimic reference parameters in python

In my recent project, I needed to migrate c# code which uses reference parameters. Unfortunately, python does not support reference parameters - In this article, we will see how can we mimic their semantics in python.

About reference parameter

A reference parameter is a local variable which points to the same storage location as the variable which was given as argument in function invocation.

We can think of a reference parameter x as an alias to the y variable that was given as argument in function invocation. Thus, any changes we do to x in the function are automatically reflected in y. Reference parameters are common in several programing languages (i.e c# or c++).

reference parameters in python

Let's define the terms in definition

Local variables, parameters and arguments

A function's local variable is a variable which can be used only in the function body.

A function's parameter is specific type of function's local variable which initial value is given in function invocation.

A function's argument is the initial value which is given to the parameter in function invocation. This value assigned to function's parameter at the beginning of the execution of the function.

Consider the following code:

local variable,parameter and argument
 def sumSquare(x1 , x2):
   sum = x1 + x2
   return sum * sum

 #print x1  # will raise <code>NameError: name 'x1'  is not defined</code>
 #print x2  # will raise <code>NameError: name 'x2'  is not defined</code>
 #print sum # will raise <code>NameError: name 'sum' is not defined</code>

 print sumSquare(1, 2) # <== A
 print sumSquare(3, 4) # <== B

The x1, x2 are parameters of sumSquare function while sum is a local variable of sumSquare function. The parameters and local variables can only be used in function body.

In A1 we call the sumSquare function with 1 and 2 arguments - Thus the initial value of x1 parameter is 1 and the initial value of x2 parameter is 2.

In A2 we call the sumSquare function with 3 and 4 arguments - Thus the initial value of x1 parameter is 3 and the initial value of x2 parameter is 4.