[ python-Bugs-1296434 ] Call by object reference sometimes call by value

SourceForge.net noreply at sourceforge.net
Sat Sep 24 00:01:09 CEST 2005


Bugs item #1296434, was opened at 2005-09-20 10:11
Message generated for change (Comment added) made by tjreedy
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1296434&group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Documentation
Group: Python 2.4
Status: Open
Resolution: None
Priority: 5
Submitted By: Alan G (abgrover)
Assigned to: Nobody/Anonymous (nobody)
Summary: Call by object reference sometimes call by value

Initial Comment:
The tutorial for 2.4.1, section 4.6 Defining Functions
states that formal parameters are introduced into the
local symbol table, making all calls call by object
reference.

The footnote points out that this means that changes to
mutable objects will be seen by the caller.  This is
also illustrated in the example involving calling the
list method append.

It would be helpful if the example could point out that
passing a value such as 1 passes an immutable object
(the constant integer value 1), and so it is impossible
to write code such as:

a = 1
def f(val):
  val = val + 1

and expect that after the call a == 2, even though val
== 2.  

My experience is that this is a confusing issue for new
users, who may not understand that val = val + 1 tosses
the object reference value passed, replacing it with a
new local object.  New users tend to see val as a
mutable object, since we just changed the value, didn't
we?  :)

----------------------------------------------------------------------

>Comment By: Terry J. Reedy (tjreedy)
Date: 2005-09-23 18:01

Message:
Logged In: YES 
user_id=593130

I agree that there are problems of beginners misunderstanding 
Python's object model.  However, the proposed fix is not exactly 
correct.  Python *always* calls functions by binding local 
parameter names to argument objects or lists or dicts thereof.  
Whenever a name is rebound to a new object, it is *always* 
unbound from the previous object, as it must be.   Mutability is 
irrelevant.  So is localness induced by a function call.

Changing locality and mutability, your example is equivalent to

a = 1
val = a
val = val + 1

a = [1]
val = a
val = val + [2]
# or
def f(val):
  val = val + [2]
f(a)

*all* of which leave 'a' unchanged, but all of which a beginner 
might think change 'a'.  Perhaps you can suggest a different 
rewording.





----------------------------------------------------------------------

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1296434&group_id=5470


More information about the Python-bugs-list mailing list