Beginner: How to copy a string?

Peter Hansen peter at engcorp.com
Thu Apr 3 21:55:53 EST 2003


dbrown2 at yahoo.com wrote:
> 
> But since everyone asked the same question "Horrors! Why in the world
> would you ever need to copy a string?" I took it as a challenge.  I
> started thinking about some not so esoteric possibilities,

Wow, it's nice to see someone trying to stand up to all that bullying
we gave him. :-)

> or hardware registers.  If the library is not written in Python (say
> it's compiled C or some other external code) then it seems the library
> could return that same pointer to the buffer or register every time,
> except it might be filled with different data. Perhaps this is not a
> correct assumption.  In any case, if I got a string buffer back from
> this kind of library I would want to copy the data to another Python
> string so I know it won't change later.

Excellent try, but I'm afraid it wouldn't work that way (unless someone
really devious deliberately tried to break how things should work).
The data returned by the external library, in order to be interfaced to 
Python, would have to create a *Python* string using calls into the 
Python interpreter (see http://www.python.org/doc/current/ext/ext.html
for more on this sort of thing).  Python would already have copied the
external data into a new area, which would then be preserved forever
in the face of everyone's futile :-) attempts to copy it.

So long as Python strings are not exposed via a pointer to some 
malicious external routine, I doubt you'll ever need to worry about
the copying thing, but I salute your attempt!

-Peter




More information about the Python-list mailing list