Unicode Objects and Codecs

Unicode Objects

Since the implementation of PEP 393 in Python 3.3, Unicode objects internally use a variety of representations, in order to allow handling the complete range of Unicode characters while staying memory efficient. There are special cases for strings where all code points are below 128, 256, or 65536; otherwise, code points must be below 1114112 (which is the full Unicode range).

Py_UNICODE* and UTF-8 representations are created on demand and cached in the Unicode object. The Py_UNICODE* representation is deprecated and inefficient.

Due to the transition between the old APIs and the new APIs, Unicode objects can internally be in two states depending on how they were created:

  • “canonical” Unicode objects are all objects created by a non-deprecated Unicode API. They use the most efficient representation allowed by the implementation.

  • “legacy” Unicode objects have been created through one of the deprecated APIs (typically PyUnicode_FromUnicode()) and only bear the Py_UNICODE* representation; you will have to call PyUnicode_READY() on them before calling any other API.

Note

The “legacy” Unicode object will be removed in Python 3.12 with deprecated APIs. All Unicode objects will be “canonical” since then. See PEP 623 for more information.

Unicode Type

These are the basic Unicode object types used for the Unicode implementation in Python:

type Py_UCS4
type Py_UCS2
type Py_UCS1
Part of the Stable ABI.

These types are typedefs for unsigned integer types wide enough to contain characters of 32 bits, 16 bits and 8 bits, respectively. When dealing with single Unicode characters, use Py_UCS4.

New in version 3.3.

type Py_UNICODE

This is a typedef of wchar_t, which is a 16-bit type or 32-bit type depending on the platform.

Changed in version 3.3: In previous versions, this was a 16-bit type or a 32-bit type depending on whether you selected a “narrow” or “wide” Unicode version of Python at build time.

type PyASCIIObject
type PyCompactUnicodeObject
type PyUnicodeObject

These subtypes of PyObject represent a Python Unicode object. In almost all cases, they shouldn’t be used directly, since all API functions that deal with Unicode objects take and return PyObject pointers.

New in version 3.3.

PyTypeObject PyUnicode_Type
Part of the Stable ABI.

This instance of PyTypeObject represents the Python Unicode type. It is exposed to Python code as str.

The following APIs are really C macros and can be used to do fast checks and to access internal read-only data of Unicode objects:

int PyUnicode_Check(PyObject *o)

Return true if the object o is a Unicode object or an instance of a Unicode subtype. This function always succeeds.

int PyUnicode_CheckExact(PyObject *o)

Return true if the object o is a Unicode object, but not an instance of a subtype. This function always succeeds.

int PyUnicode_READY(PyObject *o)

Ensure the string object o is in the “canonical” representation. This is required before using any of the access macros described below.

Returns 0 on success and -1 with an exception set on failure, which in particular happens if memory allocation fails.

New in version 3.3.

Deprecated since version 3.10, will be removed in version 3.12: This API will be removed with PyUnicode_FromUnicode().

Py_ssize_t PyUnicode_GET_LENGTH(PyObject *o)

Return the length of the Unicode string, in code points. o has to be a Unicode object in the “canonical” representation (not checked).

New in version 3.3.

Py_UCS1 *PyUnicode_1BYTE_DATA(PyObject *o)
Py_UCS2 *PyUnicode_2BYTE_DATA(PyObject *o)
Py_UCS4 *PyUnicode_4BYTE_DATA(PyObject *o)

Return a pointer to the canonical representation cast to UCS1, UCS2 or UCS4 integer types for direct character access. No checks are performed if the canonical representation has the correct character size; use PyUnicode_KIND() to select the right macro. Make sure PyUnicode_READY() has been called before accessing this.

New in version 3.3.

PyUnicode_WCHAR_KIND
PyUnicode_1BYTE_KIND
PyUnicode_2BYTE_KIND
PyUnicode_4BYTE_KIND

Return values of the PyUnicode_KIND() macro.

New in version 3.3.

Deprecated since version 3.10, will be removed in version 3.12: PyUnicode_WCHAR_KIND is deprecated.

unsigned int PyUnicode_KIND(PyObject *o)

Return one of the PyUnicode kind constants (see above) that indicate how many bytes per character this Unicode object uses to store its data. o has to be a Unicode object in the “canonical” representation (not checked).

New in version 3.3.

void *PyUnicode_DATA(PyObject *o)

Return a void pointer to the raw Unicode buffer. o has to be a Unicode object in the “canonical” representation (not checked).

New in version 3.3.

void PyUnicode_WRITE(int kind, void *data, Py_ssize_t index, Py_UCS4 value)

Write into a canonical representation data (as obtained with PyUnicode_DATA()). This macro does not do any sanity checks and is intended for usage in loops. The caller should cache the kind value and data pointer as obtained from other macro calls. index is the index in the string (starts at 0) and value is the new code point value which should be written to that location.

New in version 3.3.

Py_UCS4 PyUnicode_READ(int kind, void *data, Py_ssize_t index)

Read a code point from a canonical representation data (as obtained with PyUnicode_DATA()). No checks or ready calls are performed.

New in version 3.3.

Py_UCS4 PyUnicode_READ_CHAR(PyObject *o, Py_ssize_t index)

Read a character from a Unicode object o, which must be in the “canonical” representation. This is less efficient than PyUnicode_READ() if you do multiple consecutive reads.

New in version 3.3.

PyUnicode_MAX_CHAR_VALUE(o)

Return the maximum code point that is suitable for creating another string based on o, which must be in the “canonical” representation. This is always an approximation but more efficient than iterating over the string.

New in version 3.3.

Py_ssize_t PyUnicode_GET_SIZE(PyObject *o)

Return the size of the deprecated Py_UNICODE representation, in code units (this includes surrogate pairs as 2 units). o has to be a Unicode object (not checked).

Deprecated since version 3.3, will be removed in version 3.12: Part of the old-style Unicode API, please migrate to using PyUnicode_GET_LENGTH().

Py_ssize_t PyUnicode_GET_DATA_SIZE(PyObject *o)

Return the size of the deprecated Py_UNICODE representation in bytes. o has to be a Unicode object (not checked).

Deprecated since version 3.3, will be removed in version 3.12: Part of the old-style Unicode API, please migrate to using PyUnicode_GET_LENGTH().

Py_UNICODE *PyUnicode_AS_UNICODE(PyObject *o)
const char *PyUnicode_AS_DATA(PyObject *o)

Return a pointer to a Py_UNICODE representation of the object. The returned buffer is always terminated with an extra null code point. It may also contain embedded null code points, which would cause the string to be truncated when used in most C functions. The AS_DATA form casts the pointer to const char*. The o argument has to be a Unicode object (not checked).

Changed in version 3.3: This macro is now inefficient – because in many cases the Py_UNICODE representation does not exist and needs to be created – and can fail (return NULL with an exception set). Try to port the code to use the new PyUnicode_nBYTE_DATA() macros or use PyUnicode_WRITE() or PyUnicode_READ().

Deprecated since version 3.3, will be removed in version 3.12: Part of the old-style Unicode API, please migrate to using the PyUnicode_nBYTE_DATA() family of macros.

int PyUnicode_IsIdentifier(PyObject *o)
Part of the Stable ABI.

Return 1 if the string is a valid identifier according to the language definition, section Identifiers and keywords. Return 0 otherwise.

Changed in version 3.9: The function does not call Py_FatalError() anymore if the string is not ready.

Unicode Character Properties

Unicode provides many different character properties. The most often needed ones are available through these macros which are mapped to C functions depending on the Python configuration.

int Py_UNICODE_ISSPACE(Py_UCS4 ch)

Return 1 or 0 depending on whether ch is a whitespace character.

int Py_UNICODE_ISLOWER(Py_UCS4 ch)

Return 1 or 0 depending on whether ch is a lowercase character.

int Py_UNICODE_ISUPPER(Py_UCS4 ch)

Return 1 or 0 depending on whether ch is an uppercase character.

int Py_UNICODE_ISTITLE(Py_UCS4 ch)

Return 1 or 0 depending on whether ch is a titlecase character.

int Py_UNICODE_ISLINEBREAK(Py_UCS4 ch)

Return 1 or 0 depending on whether ch is a linebreak character.

int Py_UNICODE_ISDECIMAL(Py_UCS4 ch)

Return 1 or 0 depending on whether ch is a decimal character.

int Py_UNICODE_ISDIGIT(Py_UCS4 ch)

Return 1 or 0 depending on whether ch is a digit character.

int Py_UNICODE_ISNUMERIC(Py_UCS4 ch)

Return 1 or 0 depending on whether ch is a numeric character.

int Py_UNICODE_ISALPHA(Py_UCS4 ch)

Return 1 or 0 depending on whether ch is an alphabetic character.

int Py_UNICODE_ISALNUM(Py_UCS4 ch)

Return 1 or 0 depending on whether ch is an alphanumeric character.

int Py_UNICODE_ISPRINTABLE(Py_UCS4 ch)

Return 1 or 0 depending on whether ch is a printable character. Nonprintable characters are those characters defined in the Unicode character database as “Other” or “Separator”, excepting the ASCII space (0x20) which is considered printable. (Note that printable characters in this context are those which should not be escaped when repr() is invoked on a string. It has no bearing on the handling of strings written to sys.stdout or sys.stderr.)

These APIs can be used for fast direct character conversions:

Py_UCS4 Py_UNICODE_TOLOWER(Py_UCS4 ch)

Return the character ch converted to lower case.

Deprecated since version 3.3: This function uses simple case mappings.

Py_UCS4 Py_UNICODE_TOUPPER(Py_UCS4 ch)

Return the character ch converted to upper case.

Deprecated since version 3.3: This function uses simple case mappings.

Py_UCS4 Py_UNICODE_TOTITLE(Py_UCS4 ch)

Return the character ch converted to title case.

Deprecated since version 3.3: This function uses simple case mappings.

int Py_UNICODE_TODECIMAL(Py_UCS4 ch)

Return the character ch converted to a decimal positive integer. Return -1 if this is not possible. This macro does not raise exceptions.

int Py_UNICODE_TODIGIT(Py_UCS4 ch)

Return the character ch converted to a single digit integer. Return -1 if this is not possible. This macro does not raise exceptions.

double Py_UNICODE_TONUMERIC(Py_UCS4 ch)

Return the character ch converted to a double. Return -1.0 if this is not possible. This macro does not raise exceptions.

These APIs can be used to work with surrogates:

Py_UNICODE_IS_SURROGATE(ch)

Check if ch is a surrogate (0xD800 <= ch <= 0xDFFF).

Py_UNICODE_IS_HIGH_SURROGATE(ch)

Check if ch is a high surrogate (0xD800 <= ch <= 0xDBFF).

Py_UNICODE_IS_LOW_SURROGATE(ch)

Check if ch is a low surrogate (0xDC00 <= ch <= 0xDFFF).

Py_UNICODE_JOIN_SURROGATES(high, low)

Join two surrogate characters and return a single Py_UCS4 value. high and low are respectively the leading and trailing surrogates in a surrogate pair.

Creating and accessing Unicode strings

To create Unicode objects and access their basic sequence properties, use these APIs:

PyObject *PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
Return value: New reference.

Create a new Unicode object. maxchar should be the true maximum code point to be placed in the string. As an approximation, it can be rounded up to the nearest value in the sequence 127, 255, 65535, 1114111.

This is the recommended way to allocate a new Unicode object. Objects created using this function are not resizable.

New in version 3.3.

PyObject *PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
Return value: New reference.

Create a new Unicode object with the given kind (possible values are PyUnicode_1BYTE_KIND etc., as returned by PyUnicode_KIND()). The buffer must point to an array of size units of 1, 2 or 4 bytes per character, as given by the kind.

New in version 3.3.

PyObject *PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Return value: New reference. Part of the Stable ABI.

Create a Unicode object from the char buffer u. The bytes will be interpreted as being UTF-8 encoded. The buffer is copied into the new object. If the buffer is not NULL, the return value might be a shared object, i.e. modification of the data is not allowed.

If u is NULL, this function behaves like PyUnicode_FromUnicode() with the buffer set to NULL. This usage is deprecated in favor of PyUnicode_New(), and will be removed in Python 3.12.

PyObject *PyUnicode_FromString(const char *u)
Return value: New reference. Part of the Stable ABI.

Create a Unicode object from a UTF-8 encoded null-terminated char buffer u.

PyObject *PyUnicode_FromFormat(const char *format, ...)
Return value: New reference. Part of the Stable ABI.

Take a C printf()-style format string and a variable number of arguments, calculate the size of the resulting Python Unicode string and return a string with the values formatted into it. The variable arguments must be C types and must correspond exactly to the format characters in the format ASCII-encoded string. The following format characters are allowed:

Format Characters

Type

Comment

%%

n/a

The literal % character.

%c

int

A single character, represented as a C int.

%d

int

Equivalent to printf("%d"). 1

%u

unsigned int

Equivalent to printf("%u"). 1

%ld

long

Equivalent to printf("%ld"). 1

%li

long

Equivalent to printf("%li"). 1

%lu

unsigned long

Equivalent to printf("%lu"). 1

%lld

long long

Equivalent to printf("%lld"). 1

%lli

long long

Equivalent to printf("%lli"). 1

%llu

unsigned long long

Equivalent to printf("%llu"). 1

%zd

Py_ssize_t

Equivalent to printf("%zd"). 1

%zi

Py_ssize_t

Equivalent to printf("%zi"). 1

%zu

size_t

Equivalent to printf("%zu"). 1

%i

int

Equivalent to printf("%i"). 1

%x

int

Equivalent to printf("%x"). 1

%s

const char*

A null-terminated C character array.

%p

const void*

The hex representation of a C pointer. Mostly equivalent to printf("%p") except that it is guaranteed to start with the literal 0x regardless of what the platform’s printf yields.

%A

PyObject*

The result of calling ascii().

%U

PyObject*

A Unicode object.

%V

PyObject*, const char*

A Unicode object (which may be NULL) and a null-terminated C character array as a second parameter (which will be used, if the first parameter is NULL).

%S

PyObject*

The result of calling PyObject_Str().

%R

PyObject*

The result of calling PyObject_Repr().

An unrecognized format character causes all the rest of the format string to be copied as-is to the result string, and any extra arguments discarded.

Note

The width formatter unit is number of characters rather than bytes. The precision formatter unit is number of bytes for "%s" and "%V" (if the PyObject* argument is NULL), and a number of characters for "%A", "%U", "%S", "%R" and "%V" (if the PyObject* argument is not NULL).

1(1,2,3,4,5,6,7,8,9,10,11,12,13)

For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd, zi, zu, i, x): the 0-conversion flag has effect even when a precision is given.

Changed in version 3.2: Support for "%lld" and "%llu" added.

Changed in version 3.3: Support for "%li", "%lli" and "%zi" added.

Changed in version 3.4: Support width and precision formatter for "%s", "%A", "%U", "%V", "%S", "%R" added.

PyObject *PyUnicode_FromFormatV(const char *format, va_list vargs)
Return value: New reference. Part of the Stable ABI.

Identical to PyUnicode_FromFormat() except that it takes exactly two arguments.

PyObject *PyUnicode_FromEncodedObject(PyObject *obj, const char *encoding, const char *errors)
Return value: New reference. Part of the Stable ABI.

Decode an encoded object obj to a Unicode object.

bytes, bytearray and other bytes-like objects are decoded according to the given encoding and using the error handling defined by errors. Both can be NULL to have the interface use the default values (see Built-in Codecs for details).

All other objects, including Unicode objects, cause a TypeError to be set.

The API returns NULL if there was an error. The caller is responsible for decref’ing the returned objects.

Py_ssize_t PyUnicode_GetLength(PyObject *unicode)
Part of the Stable ABI since version 3.7.

Return the length of the Unicode object, in code points.

New in version 3.3.

Py_ssize_t PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start, PyObject *from,