newbie question
Emile van Sebille
emile at fenx.com
Sun Jan 13 11:00:04 EST 2002
"rihad" <rihad at mail.ru> wrote in message
news:mv734u00520kvagkhc13kvlq411phvddjj at 4ax.com...
> Hi, I'm new to Python and am making my way through the bundled
> tutorial. As I now understand, variables in Python are really
> references (everything is passed by object reference). If I
have this
> code:
>
> def f(n, x = []):
> # some code
>
> Even if I don't modify x inside f(), is it guaranteed that x
will
> always be [], that is, the empty list [] will never be shared
with
> some unrelated reference, which could modify it, and thus
affect what
> x binds to?
>
x is bound to the list object created at the time the code is
compiled, and all iterations of f() will share x's state. As
long as you don't modify it within x or hand out a reference to
it, normal non-introspective code won't change it. You can't
really hide anything in python though, so it is possible to
modify x. One way, for example:
>>> def f(n, x=[]): print "x is ",x
>>> f(1)
x is []
>>> f.func_defaults[0].append(0)
>>> f(1)
x is [0]
>>>
Or another way, although I'm sure this breaks in other ways:
>>> def fx(): print ['x']
>>> my_fx = fx
>>> def fy(): print ['y']
>>> fx.func_code = fy.func_code
>>> my_fx()
['y']
>>> id(fx) == id(my_fx)
1
>>>
The general rule though is that we're all consenting adults.
Don't do stuff like that.
--
Emile van Sebille
emile at fenx.com
---------
More information about the Python-list
mailing list