Mimic reference parameters in python - The Code

This article is part 4 of the series Mimic reference parameters in python

As noted in the last part, we can not change the value of the variable which was given as an argument - but we can change its attributes. Using this observation, we will use the following class to overcome this issue.

reference parameter
 class Holder:
     def __init__(self,value=None):
         self.value = value

With this class at hand, let's modify the previous function:

 class Holder:
     def __init__(self,value=None):
         self.value = value

 def tryParseInt(ss,vv):
     try:
         vv.value = int(ss)
         return True
     except:
         return False

 v1 = Holder(0) ; v2 = Holder(0)
 if tryParseInt("2",v1) and tryParseInt("3",v2):
     print v1.value*v2.value # print 6

This will work since we do not change value of the parameter - we change the value of its attribute value.

Summery

Although python does not support reference parameters we can mimic this feature with a little effort. The Holder class is a viable tool when migrating code from a language which supports reference parameters to python.