Passing arguments to function - (The fundamentals are confusing me)

Terry Reedy tjreedy at udel.edu
Tue Aug 9 23:59:19 EDT 2005


"Gregory Piñero" <gregpinero at gmail.com> wrote in message 
news:312cfe2b0508090753531e12de at mail.gmail.com...
> how references work in Python

'references' are an implementation detail and a metaconcept used to talk 
about Python but are not part of the language spec itself.

> when passing arguments into functions?

Python does not really 'pass arguments' in the way that is meant in 
name-memory_block languages like C, etc.  Being a name-object language, it 
binds parameter names in the function's local namespace to the argument 
*objects*.

<quote - OE did not quote this message correctly>
<code>

bool1=True
lst1=[1,2,3]

def func1(arg1): arg1.append(4)

def func2(arg1): arg1=False

>>func1(lst1)
>>lst1
[1,2,3,4]

>>func2(bool1)
>>bool1
True

</code>
<endquote>

>Why does my list variable get changed for the rest of the program, but
>my boolean variable doesn't.  What am I not understanding?

1. Objects have types, names (variables) do not, although you can treat one 
as it if did by only binding it to objects of a particular type even though 
the interpreter will let you rebind it to any object of any type.

2. You have not one but two 'boolean variables': bool1 and arg1 in func2. 
You rebound arg1 but did not rebind bool1, so of course arg1 remains bound 
to what it was bound to.

3. On the other hand, you mutated (extended) the list bound to both lst1 
and arg1 in func2, so of course it gets extended.

You bindings and calls are equivalent to the following:

lst1 = [1,2,3]
arg1 = lst1 # this binds arg1 to the *same* object, not a copy
arg1.append(4) # the *object* with two names is extended to [1,2,3,4]
del arg1 # delete the alias
# the list bound to lst1 and temporarily also to arg1 is still [1,2,3,4]
# you could replace the last 3 lines with lst1.append(4) to the same effect

bool1 = True
arg1 = bool1
arg1 = False # this nullifies the line above
del arg1 # ditto
# you could delete the last 3 lines since they have no net effect
# I hope you are not suprised that bool1 is still bound to True!

Terry J. Reedy






More information about the Python-list mailing list