unexpected behavior: did i create a pointer?
Alex Martelli
aleax at mac.com
Sun Sep 9 11:49:42 EDT 2007
Arnaud Delobelle <arnodel at googlemail.com> wrote:
...
> > >>> def lower_list(L):
> >
> > ... for i, x in enumerate(L):
> > ... L[i] = x.lower()
> > ...>>> s = ['STRING']
> > >>> lower_list(s)
> > >>> print s == ['string']
> > True
> >
> > >>> def lower_string(s):
> >
> > ... s = s.lower()
> > ...>>> s = "STRING"
> > >>> lower_string(s)
>
> Let's see what happens here: when lower_string(s) is called, the 's'
> which is local to lower_string is made to point to the same object as
> the global s (i.e. the string object with value "STRING"). In the
> body of the function, the statement s=s.lower() makes the local 's'
> point to a new string object returned s.lower(). Of course this has
> not effect on what object the global 's' points to.
Yep, the analogy with C pointers would work fine here:
void lower_string(char* s) {
s = <whatever>
}
would fail to have the intended effect in C just as its equivalent does
in Python (in both Python and C, rebinding the local name s has no
effect on the caller of lower_string). Add an indirection:
void lower_list(item* L) {
...
L[i] = <something>
}
this indirection (via indexing) *does* modify the memory area (visible
by the caller) to which L points.
The difference between "name=something" and "name[i]=something" is so
*HUGE* in C (and in Python) that anybody who doesn't grok that
difference just doesn't know or understand any C (nor any Python).
> What I think is a more dangerous misconception is to think that the
> assignement operator (=) has the same meaning in C and python.
I've seen the prevalence of that particular misconception drop
dramatically over the years, as a growing fraction of the people who
come to Python after some previous programming experience become more
and more likely to have been exposed to *Java*, where assignment
semantics are very close to Python (despite Java's unfortunate
complication with "unboxed" elementary scalar types, in practice a vast
majority of occurrences of "a=b" in Java have just the same semantics as
they do in Python); teaching Python semantics to people with Java
exposure is trivially easy (moving from "ALMOST every variable is an
implicit reference -- excepting int and float ones" to "EVERY variable
is an implicit reference"...).
Alex
More information about the Python-list
mailing list