How can this be?

Isaac To kkto at csis.hku.hk
Thu Feb 5 21:49:43 EST 2004


>>>>> "r" == r e s <r.s at ZZmindspring.com> writes:

    r> My problem is this ...  Module A contains the definition of a
    r> function f.  Module B contains:

    r> from A import * L = [0] print L x = f(L, 'a data string') print L

    r> When Module B is imported/reloaded (in pythonwin), the result printed
    r> in the interactive window is

    r> [0] [1]

    r> How can the list L have gotten changed??

    r> Without my posting the function def (which is very lengthy), can
    r> anyone possibly give me a clue about what might be a likely cause of
    r> this behavior?  (It *is* irregular, isn't it?  ?)

Not quite.  The function cannot change the binding that L is pointing to
that particular list object, and this is the case.  E.g.,

>>> def fun(input):
...     input[0] = 1
...     input = [2]
... 
>>> L = [0] 
>>> print L
[0]
>>> print id(L)
1075979404
>>> fun(L)
>>> print L
[1]
>>> print id(L)
1075979404

In other words, the function changes the content of L, which is allowed (as
long as the object provide some interface for you to do so).  But it cannot
change L to point to another object (here, [2]).

Regards,
Isaac.



More information about the Python-list mailing list