Pointers

Martijn Faassen m.faassen at vet.uu.nl
Tue Mar 28 09:54:39 EST 2000


Curtis Jensen <cjensen at be-research.ucsd.edu> wrote:
> I've done most of my programming in Fortran, but I have a good C
> background too.  

> Python does work on a reference setup, but it's not exactly like
> pointers.  For example:
>>>> a = 5
>>>> b = a
>>>> a = 3
>>>> print b
> 5

Sure it is!

int *a, *b;
int *immutable_3, *immutable_5;

immutable_3 = malloc(sizeof(int));
immutable_5 = malloc(sizeof(int));
*immutable_3 = 3;
*immutable_5 = 5;

a = immutable_5;
b = a;
a = immutable_3; 

printf("%d\n", *b);

> If b were a pointer to b then print b would return 3, not 5.

b is a pointer to the immutable value 5.

> There is
> the problem of mutable types and immutable types here, but the same
> thing occurs if you use a mutable type.

No, if immutable_3 and immutable_5 were mutable objects, you could mutate
them through a and have b change:

typedef struct {
  int value;
} mutable;

mutable *a, *b;
mutable *mutable_object, *other_mutable_object;

mutable_object = malloc(sizeof(mutable));
other_mutable_object = malloc(sizeof(mutable));
mutable_object->value = 3;
other_mutable_object->value = 5;

a = mutable_object;
b = a;
a->value = 5;
printf("%d\n", b->value);
/* of course this will change where a points to, instead of the
   mutable object itself */
a = other_mutable_object; /* mutable_object won't be changed */

This is equivalent to this Python:

class Mutable:
    def __init__(self, value):
        self.value = value

a = Mutable(3) 
b = a
a.value = 5
print b.value  # b.value will have changed
# of course this will change what a points to, instead of the first
# mutable object. Therefore b will remain unchanged
b = Mutable(5)

> So, pointers and python referances are not the same. 

Yes they are, but you do have to know exactly how they map to 
pointers. All variables are pointers to objects (which are *not* variables,
multiple variables may point to them). Assignment is just pointer copying.
There is *never* any value copying by assignment. New objects only get
created if you create or copy them _explicitly_. Of course, directly
after creation you usually assign them to some variable, so you can
reach them.

a = [] # creates a new list object, and a will point to that object 

If objects are immutable, all of this is functionally identical to copy
by value on assignment, which may be what's confusing.

Of course all this difficult C and pointer talk gives the impression that
this is very complicated. It's not; variables in Python are just labels
(references, pointers) to internal objects (mutable or not). Always.
 
Regards,

Martijn
-- 
History of the 20th Century: WW1, WW2, WW3?
No, WWW -- Could we be going in the right direction?



More information about the Python-list mailing list