request for advice: "PyString_FromStringAndSize(0, ..."?

Andrew Kuchling akuchlin at mems-exchange.org
Sat Oct 21 08:15:43 EDT 2000


"Alex Martelli" <aleaxit at yahoo.com> writes:
> the docs.  _Am_ I then allowed to "initialize" it (and if so
> how -- getting at the buffer with PyString_AS_STRING, or,
> how else...?) -- all the docs say is that "The data must not
> be modified in any way".  

Since you've just created the string, no other part of the system can
have a reference to it, therefore modifying the string's data is OK.
The implementation of join() in stropmodule.c does this, for example,
and I'm pretty sure I've seen this technique used in other places, too.

> And in such "authoritative"
> example sources as arrayobject.c in the NumPy sources
> I see usage patterns such as:

The author of arrayobject may simply have not known about the ability
to do this.  You could probably speed up the array module a tiny bit
by changing it to use the (0, length) form.

> So, I wonder.    What role does the 0 as the first argument
> to PyString_FromStringAndSize possibly play, unless that
> uninitialized data can then be gotten at and initialized?  Is

There's a comment at the top of Objects/stringobject.c:
   A common practice to allocate a string and then fill it in or
   change it must be done carefully.  It is only allowed to change the
   contents of the string if the obect was gotten from
   newsizedstringobject() with a NULL first argument, because in the
   future these routines may try to do even more sharing of objects.

So I would think you can rely on this behaviour.

--amk



More information about the Python-list mailing list