How can you copy (clone) a string?

Tom nospam at nospam.com
Tue Oct 3 10:45:49 EDT 2000


I don't think you can.

The copy module doesn't actually copy strings, it just increases their ref
count and returns a new reference (it does this for most types).  I assume
that the reason it does this is because you can't copy them: the
implementation is free to decide to only keep a single copy of identical
immutables.  Even if you have two completely unrelated, but identical
strings, they can have the same id.

Why do you need seperate copies?  In my case, I wanted to make seperate
copies because I was concerned with thread-safety, but I now been told (by
c.l.p.) that the atomic, immutable types that can't be copied can be shared
between threads.

Tom.

<Peter.Rupp at ual.com> wrote in message
news:mailman.970582146.5958.python-list at python.org...
> All,
> I have a bonafide need to create copies of strings in a python program
> (as opposed to a reference to the original).  I tried using the 'copy'
> module using both it's 'copy' and 'deepcopy' methods to no avail.  I'm
> using the "id" function to determine whether I have a new string or a
> reference to an existing string.
>
> Let me illustrate......
>
> from copy import *
> a='a'
> id(a)
> 1073972424
> b=deepcopy(a)
> id(b)
> 1073972424
>
> Huh?   This is supposed to give me a new string refererence...as noted
> in the book 'Python Essential Reference' by David M. Beazley (pp. 95 in
> the last paragraph under the heading "NOTES", where he describes the
> feature as "This module can be used with simple types such as integers
> and strings, but there's little need to do so."
>
> Well, I really do have a need here ;-)
>
> Any help or suggestions would be appreciated...please respond via email
> as I cannot get news here.  Thanks in advance.
>
> ==pete==
> P. A. Rupp  - United Airlines Corp.
> peter.rupp at ual.com
> 847-700-3226
>
>





More information about the Python-list mailing list