Pass variable by reference

Steven D'Aprano steve at pearwood.info
Tue May 6 04:18:52 EDT 2014


On Mon, 05 May 2014 17:39:44 -0700, Satish Muthali wrote:

> Hello experts,
> 
> I have a burning question on how to pass variable by reference in
> Python. I understand that  the data type has to be mutable.

Python provides neither pass-by-reference nor pass-by-value argument 
passing. Please read this for an explanation of why people sometimes 
think that it does, and what Python actually does instead:

http://import-that.dreamwidth.org/1130.html


To get an effect *similar* to pass-by-reference, you can wrap your 
variable in a list, and then only operate on the list item. For example:


one = [1]
two = [2]

def swap(a, b):
    a[0], b[0] = b[0], a[0]

swap(one, two)
print one[0], two[0]
=> will print "2 1"


But note carefully that in the swap function I do not assign directly to 
the arguments a and b, only to their items a[0] and b[0]. If you assign 
directly to a and b, you change the local variables.

# This does not work.
def swap(a, b):
    a, b = b, a


Rather than trying to fake pass-by-reference semantics, it is much better 
to understand Python's capabilities and learn how to use it to get the 
same effect. For example, instead of writing a swap procedure, it is much 
simpler to just do this:

one = 1
two = 2
one, two = two, one
print one, two
=> will print "2 1"

> For example, here’s the issue I am running in to:
> 
> I am trying to extract the PostgreSQL DB version for example:
> 
> pgVer = [s.split() for s in os.popen("psql
> --version").read().splitlines()]
>     print pgVer[0]
>     for i, var in enumerate(pgVer[0]):
> 	    if i == len(pgVer[0]) - 1:
> 		    pgversion = var
>
> I would now like to pass ‘pgversion’ (where the value of pgversion is
> 9.3.4) by reference, for example:
> 
> I want to nuke /var/lib/postgresql/9.3.4/main/data , however
> programatically I want it to be as:  /var/lib/postgresql/<value of
> pgversion>/main/data

I don't understand this. I think you mean that you want to delete a file, 
but you don't know the pathname of the file until you have extracted the 
version number as a string.

path = "/var/lib/postgresql/%s/main/data"
os.unlink(path % pgversion)

will probably do what you want. Pass-by-reference doesn't come into this.

If this is not what you mean, please explain in more detail.



-- 
Steven



More information about the Python-list mailing list