Pass by reference?

Grant Edwards ge at nowhere.none
Thu May 25 11:54:43 EDT 2000


In article <392CFBD8.E5173DFD at ecs.soton.ac.uk>, Jacek Generowicz wrote:

>> Also the following program proves to me that arguments are passed by value
>> and not by reference:
>
>No, it doesn't, but I agree that if you do not keep in mind exactly what `='
>does in Python, then you are likely to think so.

It sort of depends on how you think about it.  As a long-time C
programemr, I generally take the viewpoint that in Python
variables are passed by value, but all variables are pointers.
(And many of the pointers are pointing to "const" objects that
can't be modified.) If you're a C programmer, you can think of
it like this:

void foo(char *p)
  {
  printf("%s\n",p);
  p = "abcd";
  printf("%s\n",p);
  }

void main(void)
  {
  char *s;
  s = "qwer";
  printf("%s\n",s);
  foo(s);
  printf("%s\n",s);
  }

In foo(), the assignment statement 'p = "asdf"' doesn't change
the value of the object to which p originally pointed -- rather
it makes p point to a different object.  This is exactly what
Python does.

There _are_ times in Python when you can modify the object to
which a parameter points -- which, in C would be something
like:

void foo(char *p)
  {
  p[2] = 'x';
  }

However, 
 
 1) some objects are not mutable, so this paradigm can't be used.
 
 2) side effects like this are often the cause of bugs.

 3) stylistically, those of us who learned Scheme before we
    learned Python generally prefer a more functional approach.

-- 
Grant Edwards                   grante             Yow!  Are you guys lined up
                                  at               for the METHADONE PROGRAM
                               visi.com            or FOOD STAMPS??



More information about the Python-list mailing list