[Python-Dev] cpython: fix compiler warning by implementing this more cleverly

Victor Stinner victor.stinner at haypocalc.com
Wed Nov 23 10:40:36 CET 2011

Le Mercredi 23 Novembre 2011 01:49:28 Terry Reedy a écrit :
> The one-liner could be followed by
>    assert(kind==1 || kind==2 || kind==4)
> which would also serve to remind the reader of the possibilities.

For a ready string, kind must be 1, 2 or 4. We might rename "kind" to 
"charsize" because its value changed from 1, 2, 3 to 1, 2, 4 (to make it easy 
to compute the size of a string: length * kind).

You are not supposed to see the secret kind==0 case. This value is only used 
for string created by _PyUnicode_New() and not ready yet:

  str = _PyUnicode_New()
  /* use str */
  assert(PyUnicode_KIND(str) == 0);
  if (PyUnicode_READY(str) < 0)
     /* error */
  assert(PyUnicode_KIND(str) != 0); /* kind is 1, 2, 4 */

Thanks to the effort of t0rsten, Martin and me, quite all functions use the 
new API (PyUnicode_New). For example, PyUnicode_AsRawUnicodeEscapeString() 
starts by ensuring that the string is ready.

For your information, PyUnicode_KIND() fails with an assertion error in debug 
mode if the string is not ready.


I don't have an opinion about the one-liner vs the switch :-)

But if you want to fix compiler warnings, you should use "enum PyUnicode_Kind" 
type and PyUnicode_WCHAR_KIND should be removed from the enum.


More information about the Python-Dev mailing list