lazy <[EMAIL PROTECTED]> wrote:

> I want to pass a string by reference. I understand that strings are
> immutable, but Im not
> going to change the string in the function, just to aviod the overhead
> of copying(when pass-by-value) because the
> strings are long and this function will be called over and over
> again.

You'll find it is pretty hard to get Python to copy a string even if you 
wanted it to. About the only way is to break it apart and then construct a 
new string with the same value from it.

>>> s = "some long string"
>>> id(s)
12944352
>>> copyofs = s[:]
>>> id(copyofs)
12944352
>>> copyofs = s[:-1]+s[-1:]
>>> id(copyofs)
12944992
>>> def fn(foo):
        print id(foo)
        return foo

>>> fn(s)
12944352
'some long string'
>>> id(fn(s))
12944352
12944352

And sometimes two strings created separately magically become the same 
string (not that should you assume this will happen, just that it might, 
and the behaviour will vary according to a lot of factors):

>>> s1 = "abc"
>>> id(s1)
12956256
>>> s2 = "abc"
>>> id(s2)
12956256
>>> s1 = "pqr stu"
>>> id(s1)
12956288
>>> s2 = "pqr stu"
>>> id(s2)
12956192
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to