String Formatting Helpers

HPy string formatting helpers.

Note: these functions are runtime helper functions, i.e., they are not part of the HPy context ABI, but are available to HPy extensions to incorporate at compile time.

The formatting helper functions are: HPyUnicode_FromFormat, HPyUnicode_FromFormatV, and HPyErr_Format.

Supported Formatting Units

%% - The literal % character.

Compatible with C (s)printf:

%c [int]

%d [int]

%u [unsigned int]

%ld [long]

%li [long]

%lu [unsigned long]

%lld [long long]

%lli [long long]

%llu [unsigned long long]

%zd [HPy_ssize_t]

%zi [HPy_ssize_t]

%zu [size_t]

%i [int]

%x [int]

%s [const char*]

%p [const void*]

Guaranteed to start with the literal ‘0x’ regardless of what the platform’s printf yields. However, there is no guarantee for zero-padding after the ‘0x’ prefix. Some systems pad the pointer to 32 or 64 digits depending on the architecture, some do not zero pad at all. Moreover, there is no guarantee whether the letters will be capitalized or not.

Python specific:

%A [HPy]

The result of calling HPy_Ascii.

%U [HPy]

A Unicode object.

%V [HPy, const char*]

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

%S [HPy]

The result of calling HPy_Str.

%R [HPy]

The result of calling HPy_Repr.

Additional flags:

The format is %[0]{width}.{precision}{formatting-unit}.

The precision flag for numbers gives the minimal number of digits (i.e., excluding the minus sign). Shorter numbers are padded with zeros. For strings it gives the maximum number of characters, i.e., the string may be shortened if it is longer than precision.

The width determines how many characters should be output. If the formatting result with width flag applied is shorter, then it is padded from left with spaces. If it is longer, the result will not be shortened.

The 0 flag is supported only for numeric units: if present, the number is padded to desired width with zeros instead of spaces. Unlike with spaces padding, the minus sign is shifted to the leftmost position with zero padding.

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 HPy argument is HPy_NULL), and a number of characters for %A, %U, %S, %R and %V (if the HPy argument is not HPy_NULL).

Compatibility with CPython API

HPy is more strict in these cases:

CPython API ignores width, precision, zero-padding flag for formatting units that do not support them: %c and %p, but HPy raises a system error in such cases.

CPython API ignores zero-padding for “string” formatting units, while HPy raises a system error in such cases.

Note: users should not rely on these system errors, as HPy may choose to support some of those flags in the future.