Unicode オブジェクトと codec

Unicode オブジェクト

Python3.3 の PEP 393 実装から、メモリ効率を維持しながらUnicode文字の完全な範囲を扱えるように、Unicodeオブジェクトは内部的に多様な表現形式を用いています。すべてのコードポイントが128、256または65536以下の文字列に対して特別なケースが存在しますが、それ以外ではコードポイントは1114112以下(これはすべてのUnicode範囲です)でなければなりません。

Py_UNICODE* 表現形式および UTF-8表現形式はオンデマンドで作成され、Unicode オブジェクト内にキャッシュされます。Py_UNICODE* 表現は推奨されず、非効率です。

古いAPIから新しいAPIへの移行の影響で、 Unicode オブジェクトの内部の状態は2通りあります。これはオブジェクトの作られ方によって決まります。

  • "正統な" Unicode オブジェクトは、非推奨ではないUnicode APIで作成されたすべてのオブジェクトです。これらのオブジェクトは実装が許すかぎり最も効率の良い表現形式を使用します。

  • "古い" Unicode オブジェクトは、非推奨の API (たいていは PyUnicode_FromUnicode()) で作成されたオブジェクトで、 Py_UNICODE* 表現形式しか持ってません; 他の API を呼び出す前に、このオブジェクトに対し PyUnicode_READY() を呼び出す必要があるでしょう。

注釈

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 型

以下は Python の Unicode 実装に用いられている基本 Unicode オブジェクト型です:

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

これらの型は、それぞれ、32ビット、16ビット、そして8ビットの文字を保持するのに充分な幅を持つ符号なしの整数型のtypedefです。単一のUnicode文字を扱う場合は、 Py_UCS4 を用いてください。

バージョン 3.3 で追加.

type Py_UNICODE

これは、wchar_t のtypedef で、プラットフォームに依存して16ビットか32ビットの型になります。

バージョン 3.3 で変更: 以前のバージョンでは、Pythonをビルドした際に "narrow" または "wide" Unicode バージョンのどちらを選択したかによって、 16ビットか32ビットのどちらかの型になっていました。

type PyASCIIObject
type PyCompactUnicodeObject
type PyUnicodeObject

これらの PyObject のサブタイプは Python Unicode オブジェクトを表現します。 Unicode オブジェクトを扱う全ての API 関数は PyObject へのポインタを受け取って PyObject へのポインタを返すので、ほとんどの場合、これらの型を直接使うべきではありません。

バージョン 3.3 で追加.

PyTypeObject PyUnicode_Type
Part of the Stable ABI.

この PyTypeObject のインスタンスは、Python Unicode型を表します。これは、Pythonコードに str として露出されます。

以下の API は実際には C マクロで、Unicode オブジェクト内部の読み取り専用データに対するチェックやアクセスを高速に行います:

int PyUnicode_Check(PyObject *o)

オブジェクト o が Unicode オブジェクトか Unicode 型のサブタイプのインスタンスである場合に真を返します。この関数は常に成功します。

int PyUnicode_CheckExact(PyObject *o)

オブジェクト o が Unicode オブジェクトだがサブタイプのインスタンスでない場合に真を返します。この関数は常に成功します。

int PyUnicode_READY(PyObject *o)

文字列オブジェクト o が "正統な" 表現形式であることを保証します。 このマクロは、下で説明しているどのアクセスマクロを使うときも必要となります。

成功のときには 0 を返し、失敗のときには例外を設定し -1 を返します。 後者は、メモリ確保に失敗したときに特に起きやすいです。

バージョン 3.3 で追加.

バージョン 3.10 で非推奨、バージョン 3.12 で削除予定: This API will be removed with PyUnicode_FromUnicode().

Py_ssize_t PyUnicode_GET_LENGTH(PyObject *o)

Unicode 文字列のコードポイントでの長さを返します。 o は "正統な" 表現形式の Unicode オブジェクトでなければなりません (ただしチェックはしません)。

バージョン 3.3 で追加.

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

文字に直接アクセスするために、 UCS1, UCS2, UCS4 のいずれかの整数型にキャストされた正統な表現形式へのポインタを返します。 正統な表現が適正な文字サイズになっているかどうかのチェックはしません; PyUnicode_KIND() を使って正しいマクロを選んでください。 このオブジェクトにアクセスする前に、忘れずに PyUnicode_READY() を呼び出してください。

バージョン 3.3 で追加.

PyUnicode_WCHAR_KIND
PyUnicode_1BYTE_KIND
PyUnicode_2BYTE_KIND
PyUnicode_4BYTE_KIND

PyUnicode_KIND() マクロの返り値です。

バージョン 3.3 で追加.

バージョン 3.10 で非推奨、バージョン 3.12 で削除予定: PyUnicode_WCHAR_KIND is deprecated.

unsigned int PyUnicode_KIND(PyObject *o)

この Unicode がデータを保存するのに1文字あたり何バイト使っているかを示す PyUnicode 種別の定数 (上を読んでください) のうち1つを返します。 o は "正統な" 表現形式の Unicode オブジェクトでなければなりません (ただしチェックはしません)。

バージョン 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).

バージョン 3.3 で追加.

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

正統な表現形式となっている (PyUnicode_DATA() で取得した) data に書き込みます。 このマクロは正常性のチェックを一切行わない、ループで使われるためのものです。 呼び出し側は、他のマクロを呼び出して取得した kind 値と data ポインタをキャッシュすべきです。 index は文字列の (0始まりの) インデックスで、 value はその場所に書き込まれることになる新しいコードポイントの値です。

バージョン 3.3 で追加.

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

正統な表現形式となっている (PyUnicode_DATA() で取得した) data からコードポイントを読み取ります。 チェックや事前確認のマクロ呼び出しは一切行われません。

バージョン 3.3 で追加.

Py_UCS4 PyUnicode_READ_CHAR(PyObject *o, Py_ssize_t index)

Unicode オブジェクト o から文字を読み取ります。 この Unicode オブジェクトは "正統な" 表現形式でなければなりません。 何度も連続して読み取る場合には、このマクロは PyUnicode_READ() よりも非効率的です。

バージョン 3.3 で追加.

PyUnicode_MAX_CHAR_VALUE(o)

o に基づいて他の文字列を作るのに適した最大のコードポイントを返します。 この Unicode オブジェクトは "正統な" 表現形式でなければなりません。 この値は常に概算値ですが、文字列全体を調べるよりも効率的です。

バージョン 3.3 で追加.

Py_ssize_t PyUnicode_GET_SIZE(PyObject *o)

非推奨の Py_UNICODE 表現形式のサイズをコード単位で返します (サロゲートペアを2つとしています)。 o は Unicode オブジェクトでなければなりません (ただしチェックはしません)。

バージョン 3.3 で非推奨、バージョン 3.12 で削除予定: 古いスタイルの Unicode APIの一部なので、 PyUnicode_GET_LENGTH() を使用するように移行してください。

Py_ssize_t PyUnicode_GET_DATA_SIZE(PyObject *o)

非推奨の Py_UNICODE 表現形式のサイズをバイト単位で返します。 o は Unicode オブジェクトでなければなりません (ただしチェックはしません)。

バージョン 3.3 で非推奨、バージョン 3.12 で削除予定: 古いスタイルの Unicode APIの一部なので、 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).

バージョン 3.3 で変更: このマクロは今では非効率なものになりました。 というのも、多くのケースで Py_UNICODE 表現形式が登場せず、作成されず、そして失敗し得ます (例外を設定して NULL を返します)。 コードを修正して、 PyUnicode_nBYTE_DATA() マクロを使うか PyUnicode_WRITE()PyUnicode_READ() を使うようにしてください。

バージョン 3.3 で非推奨、バージョン 3.12 で削除予定: 古いスタイルの Unicode APIの一部なので、 PyUnicode_nBYTE_DATA() 系のマクロを使用するように移行してください。

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 識別子 (identifier) およびキーワード (keyword). Return 0 otherwise.

バージョン 3.9 で変更: The function does not call Py_FatalError() anymore if the string is not ready.

Unicode 文字プロパティ

Unicode は数多くの異なる文字プロパティ (character property) を提供しています。よく使われる文字プロパティは、以下のマクロで利用できます。これらのマクロは Python の設定に応じて、各々 C の関数に対応付けられています。

int Py_UNICODE_ISSPACE(Py_UCS4 ch)

ch が空白文字かどうかに応じて 1 または 0 を返します。

int Py_UNICODE_ISLOWER(Py_UCS4 ch)

ch が小文字かどうかに応じて 1 または 0 を返します。

int Py_UNICODE_ISUPPER(Py_UCS4 ch)

ch が大文字かどうかに応じて 1 または 0 を返します。

int Py_UNICODE_ISTITLE(Py_UCS4 ch)

ch がタイトルケース文字 (titlecase character) かどうかに応じて 1 または 0 を返します。

int Py_UNICODE_ISLINEBREAK(Py_UCS4 ch)

ch が改行文字かどうかに応じて 1 または 0 を返します。

int Py_UNICODE_ISDECIMAL(Py_UCS4 ch)

ch が decimal 文字かどうかに応じて 1 または 0 を返します。

int Py_UNICODE_ISDIGIT(Py_UCS4 ch)

ch が digit 文字かどうかに応じて 1 または 0 を返します。

int Py_UNICODE_ISNUMERIC(Py_UCS4 ch)

ch が数字 (numeric) 文字かどうかに応じて 1 または 0 を返します。

int Py_UNICODE_ISALPHA(Py_UCS4 ch)

ch がアルファベット文字かどうかに応じて 1 または 0 を返します。

int Py_UNICODE_ISALNUM(Py_UCS4 ch)

ch が英数文字かどうかに応じて 1 または 0 を返します。

int Py_UNICODE_ISPRINTABLE(Py_UCS4 ch)

ch が文字が印字可能な文字かどうかに基づいて 1 または 0 を返します。 非印字可能文字は、 Unicode 文字データベースで "Other" または "Separator" と定義されている文字の、印字可能と見なされる ASCII space (0x20) 以外のものです。 (なお、この文脈での印字可能文字は、文字列に repr() が呼び出されるときにエスケープすべきでない文字のことです。これは sys.stdoutsys.stderr に書き込まれる文字列の操作とは関係ありません。)

以下の API は、高速に直接文字変換を行うために使われます:

Py_UCS4 Py_UNICODE_TOLOWER(Py_UCS4 ch)

ch を小文字に変換したものを返します。

バージョン 3.3 で非推奨: この関数は単純な大文字小文字変換を使ってます。

Py_UCS4 Py_UNICODE_TOUPPER(Py_UCS4 ch)

ch を大文字に変換したものを返します。

バージョン 3.3 で非推奨: この関数は単純な大文字小文字変換を使ってます。

Py_UCS4 Py_UNICODE_TOTITLE(Py_UCS4 ch)

ch をタイトルケース文字に変換したものを返します。

バージョン 3.3 で非推奨: この関数は単純な大文字小文字変換を使ってます。

int Py_UNICODE_TODECIMAL(Py_UCS4 ch)

ch を 10 進の正の整数に変換したものを返します。不可能ならば -1 を返します。このマクロは例外を送出しません。

int Py_UNICODE_TODIGIT(Py_UCS4 ch)

ch を一桁の 2 進整数に変換したものを返します。不可能ならば -1 を返します。このマクロは例外を送出しません。

double Py_UNICODE_TONUMERIC(Py_UCS4 ch)

ch を double に変換したものを返します。不可能ならば -1.0 を返します。このマクロは例外を送出しません。

これらの API はサロゲートにも使えます:

Py_UNICODE_IS_SURROGATE(ch)

ch がサロゲートかどうか (0xD800 <= ch <= 0xDFFF) をチェックします。

Py_UNICODE_IS_HIGH_SURROGATE(ch)

ch が上位サロゲートかどうか (0xD800 <= ch <= 0xDBFF) をチェックします。

Py_UNICODE_IS_LOW_SURROGATE(ch)

ch が下位サロゲートかどうか (0xDC00 <= ch <= 0xDFFF) をチェックします。

Py_UNICODE_JOIN_SURROGATES(high, low)

2つのサロゲート文字を組み合わせて単一の Py_UCS4 値を返します。 highlow はそれぞれサロゲートペアの前半分と後半分です。

Unicode 文字列の生成とアクセス

Unicode オブジェクトを生成したり、Unicode のシーケンスとしての基本的なプロパティにアクセスしたりするには、以下の API を使ってください:

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

新しい Unicode オブジェクトを生成します。 maxchar は文字列に並べるコードポイントの正しい最大値にすべきです。 その値は概算値として 127, 255, 65535, 1114111 の一番近い値に切り上げられます。

これは新しい Unicode オブジェクトを生成する推奨された方法です。 この関数を使って生成されたオブジェクトはサイズ変更は不可能です。

バージョン 3.3 で追加.

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

与えられた kind (取り得る値は PyUnicode_1BYTE_KIND などの PyUnicode_KIND() が返す値です) の Unicode オブジェクトを生成します。 buffer は、与えられた kind に従って1文字あたり 1, 2, 4 バイトのいずれかを単位として、長さ size の配列へのポインタでなければなりません。

バージョン 3.3 で追加.

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

char 型バッファ u から Unicode オブジェクトを生成します。 u の内容は UTF-8 でエンコードされているものとします。 バッファの内容は新たなオブジェクトにコピーされます。 バッファが NULL でない場合、帰り値は共有されたオブジェクトになることがあります。 つまり、この関数が返す Unicode オブジェクトの変更は許されていません。

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.

UTF-8 エンコードされたnull終端のchar 型バッファ u から Unicode オブジェクトを生成します。

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:

書式指定文字

備考

%%

n/a

リテラルの % 文字

%c

int

C の整数型で表現される単一の文字。

%d

int

printf("%d") と同等。 1

%u

unsigned int

printf("%u") と同等。 1

%ld

long

printf("%ld") と同等。 1

%li

long

printf("%li") と同等。 1

%lu

unsigned long

printf("%lu") と同等。 1

%lld

long long

printf("%lld") と同等。 1

%lli

long long

printf("%lli") と同等。 1

%llu

unsigned long long

printf("%llu") と同等。 1

%zd

Py_ssize_t

printf("%zd") と同等。 1

%zi

Py_ssize_t

printf("%zi") と同等。 1

%zu

size_t

printf("%zu") と同等。 1

%i

int

printf("%i") と同等。 1

%x

int

printf("%x") と同等。 1

%s

const char*

null で終端された C の文字列。

%p

const void*

C ポインタの 16 進表記。printf("%p") とほとんど同じですが、プラットフォームにおける printf の定義に関わりなく先頭にリテラル 0x が付きます。

%A

PyObject*

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*

PyObject_Str() の戻り値。

%R

PyObject*

PyObject_Repr() の戻り値。

識別できない書式指定文字があった場合、残りの書式文字列はそのまま出力文字列にコピーされ、残りの引数は無視されます。

注釈

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.

バージョン 3.2 で変更: "%lld", "%llu" のサポートが追加されました。

バージョン 3.3 で変更: "%li", "%lli", "%zi" のサポートが追加されました。

バージョン 3.4 で変更: "%s", "%A", "%U", "%V", "%S", "%R" での幅フォーマッタおよび精度フォーマッタのサポートが追加されました。

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

ちょうど2つの引数を取ることを除いて、 PyUnicode_FromFormat() と同じです。

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

エンコードされている obj を Unicode オブジェクトにデコードします。

bytesbytearray や他の bytes-like objects は、与えられた encoding に従ってデコードされ、 errors で定義されたエラーハンドリングが使われます。 これらの引数は両方とも NULL にでき、その場合この API はデフォルト値を使います (詳しことは 組み込み codec (built-in codec) を参照してください)。

その他のUnicodeオブジェクトを含むオブジェクトは TypeError 例外を引き起こします。

この API は、エラーが生じたときには NULL を返します。呼び出し側は返されたオブジェクトに対し参照カウンタを 1 つ減らす (decref) する責任があります。

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

Unicode オブジェクトの長さをコードポイントで返します。

バージョン 3.3 で追加.

Py_ssize_t PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start, PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)

ある Unicode オブジェクトから他へ文字をコピーします。 この関数は必要なときに文字変換を行い、可能な場合は memcpy() へ差し戻します。 失敗のときには -1 を返し、例外を設定します。そうでない場合は、コピーした文字数を返します。

バージョン 3.3 で追加.

Py_ssize_t PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length, Py_UCS4 fill_char)

文字列を文字で埋めます: unicode[start:start+length]fill_char を埋めることになります。

fill_char が文字列の最大文字よりも大きい場合や、文字列2つ以上の参照を持ってた場合は失敗します。

書き込んだ文字数を返すか、失敗のときには -1 を返し例外を送出します。

バージョン 3.3 で追加.

int PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 character)
Part of the Stable ABI since version 3.7.

文字列に文字を書き込みます。 文字列は PyUnicode_New() で作成しなければなりません。 Unicode 文字列は不変とされているので、この文字列は共有されていたり、これまでにハッシュ化されていてはいけません。

この関数は unicode が Unicode オブジェクトであること、インデックスが範囲内であること、オブジェクトが安全に変更できる (つまり参照カウントが1である) ことをチェックします。

バージョン 3.3 で追加.

Py_UCS4 PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
Part of the Stable ABI since version 3.7.

文字列から文字を読み取ります。 マクロ版の PyUnicode_READ_CHAR() とは対照的に、この関数は unicode が Unicode オブジェクトであること、インデックスが範囲内であることをチェックします。

バージョン 3.3 で追加.

PyObject *PyUnicode_Substring(PyObject *str, Py_ssize_t start, Py_ssize_t end)
Return value: New reference. Part of the Stable ABI since version 3.7.

str の文字インデックス start (端点を含む) から文字インデックス end (端点を含まず) までの部分文字列を返します。 負のインデックスはサポートされていません。

バージョン 3.3 で追加.

Py_UCS4 *PyUnicode_AsUCS4(PyObject *u, Py_UCS4 *buffer, Py_ssize_t buflen, int copy_null)
Part of the Stable ABI since version 3.7.

文字列 u を UCS4 のバッファへコピーします。 copy_null が設定されている場合は、ヌル文字も含めます。 エラーが起きたときは、 NULL を返し、例外を設定します (buflenu の長さより短かった場合については、 SystemError が設定されます)。 成功したときは buffer を返します。

バージョン 3.3 で追加.

Py_UCS4 *PyUnicode_AsUCS4Copy(PyObject *u)
Part of the Stable ABI since version 3.7.

文字列 uPyMem_Malloc() でメモリ確保された新しい UCS4 型のバッファにコピーします。 これが失敗した場合は、 NULL を返し MemoryError をセットします。 返されたバッファは必ず null コードポイントが追加されています。

バージョン 3.3 で追加.

廃止予定の Py_UNICODE API群

バージョン 3.3 で非推奨、バージョン 3.12 で削除予定.

これらのAPI 関数は PEP 393 の実装により廃止予定です。Python 3.x では削除されないため、拡張モジュールはこれらの関数を引き続き使えますが、これらの関数の使用はパフォーマンスとメモリに影響があることを念頭に置いてください。

PyObject *PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Return value: New reference.

size で指定された長さを持つ Py_UNICODE 型バッファ u から Unicode オブジェクトを生成します。 uNULL にしてもよく、その場合オブジェクトの内容は未定義です。 バッファに必要な情報を埋めるのはユーザの責任です。 バッファの内容は新たなオブジェクトにコピーされます。

バッファが NULL でない場合、戻り値は共有されたオブジェクトになることがあります。 従って、この関数が返す Unicode オブジェクトを変更してよいのは uNULL のときだけです。

バッファが NULL の場合、文字列の内容が埋められたなら PyUnicode_KIND() のようなアクセスマクロを使う前に PyUnicode_READY() を呼び出さなければなりません。

バージョン 3.3 で非推奨、バージョン 3.12 で削除予定: Part of the old-style Unicode API, please migrate to using PyUnicode_FromKindAndData(), PyUnicode_FromWideChar(), or PyUnicode_New().

Py_UNICODE *PyUnicode_AsUnicode(PyObject *unicode)

Return a read-only pointer to the Unicode object's internal Py_UNICODE buffer, or NULL on error. This will create the Py_UNICODE* representation of the object if it is not yet available. The buffer is always terminated with an extra null code point. Note that the resulting Py_UNICODE string may also contain embedded null code points, which would cause the string to be truncated when used in most C functions.

バージョン 3.3 で非推奨、バージョン 3.12 で削除予定: Part of the old-style Unicode API, please migrate to using PyUnicode_AsUCS4(), PyUnicode_AsWideChar(), PyUnicode_ReadChar() or similar new APIs.

PyObject *PyUnicode_TransformDecimalToASCII(Py_UNICODE *s, Py_ssize_t size)
Return value: New reference.

与えられた長さ size を持つ Py_UNICODE 型のバッファにある全ての decimal digit を、それらの10進の値に対応する 0 から 9 までの ASCII 数字に置き換えた Unicode オブジェクトを生成します。 例外が起きた場合は NULL を返します。

バージョン 3.3 で非推奨、バージョン 3.11 で削除予定: Part of the old-style Py_UNICODE API; please migrate to using Py_UNICODE_TODECIMAL().

Py_UNICODE *PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)

Like PyUnicode_AsUnicode(), but also saves the Py_UNICODE() array length (excluding the extra null terminator) in size. Note that the resulting Py_UNICODE* string may contain embedded null code points, which would cause the string to be truncated when used in most C functions.

バージョン 3.3 で追加.

バージョン 3.3 で非推奨、バージョン 3.12 で削除予定: Part of the old-style Unicode API, please migrate to using PyUnicode_AsUCS4(), PyUnicode_AsWideChar(), PyUnicode_ReadChar() or similar new APIs.

Py_ssize_t PyUnicode_GetSize(PyObject *unicode)
Part of the Stable ABI.

非推奨の Py_UNICODE 表現形式のサイズをコード単位で返します (サロゲートペアを2つとしています)。

バージョン 3.3 で非推奨、バージョン 3.12 で削除予定: 古いスタイルの Unicode APIの一部なので、 PyUnicode_GET_LENGTH() を使用するように移行してください。

PyObject *PyUnicode_FromObject(PyObject *obj)
Return value: New reference. Part of the Stable ABI.

Unicode のサブタイプのインスタンスを、必要な場合は本物の Unicode オブジェクトにコピーします。 obj が (サブタイプではない) 既に本物の Unicode オブジェクトだった場合は、参照カウントを1つ増やした参照を返します。

Unicode やそのサブタイプ以外のオブジェクトでは TypeError が引き起こされます。

ロケールエンコーディング

現在のロケールエンコーディングはオペレーティングシステムのテキストをデコードするのに使えます。

PyObject *PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len, const char *errors)
Return value: New reference. Part of the Stable ABI since version 3.7.

Decode a string from UTF-8 on Android and VxWorks, or from the current locale encoding on other platforms. The supported error handlers are "strict" and "surrogateescape" (PEP 383). The decoder uses "strict" error handler if errors is NULL. str must end with a null character but cannot contain embedded null characters.

PyUnicode_DecodeFSDefaultAndSize() を使って (Python の起動時に読み込まれるロケールエンコーディングの) Py_FileSystemDefaultEncoding の文字列をデコードします。

This function ignores the Python UTF-8 Mode.

参考

Py_DecodeLocale() 関数。

バージョン 3.3 で追加.

バージョン 3.7 で変更: この関数は、 Android 以外では現在のロケールエンコーディングを surrogateescape エラーハンドラで使うようになりました。 以前は、 Py_DecodeLocale()surrogateescape で使われ、現在のロケールエンコーディングは strict で使われていました。

PyObject *PyUnicode_DecodeLocale(const char *str, const char *errors)
Return value: New reference. Part of the Stable ABI since version 3.7.

PyUnicode_DecodeLocaleAndSize() と似てますが、 strlen() を使って文字列の長さを計算します。

バージョン 3.3 で追加.

PyObject *PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Return value: New reference. Part of the Stable ABI since version 3.7.

Encode a Unicode object to UTF-8 on Android and VxWorks, or to the current locale encoding on other platforms. The supported error handlers are "strict" and "surrogateescape" (PEP 383). The encoder uses "strict" error handler if errors is NULL. Return a bytes object. unicode cannot contain embedded null characters.

PyUnicode_EncodeFSDefault() を使って (Python の起動時に読み込まれるロケールエンコーディングの) Py_FileSystemDefaultEncoding の文字列へエンコードします。

This function ignores the Python UTF-8 Mode.

参考

Py_EncodeLocale() 関数。

バージョン 3.3 で追加.

バージョン 3.7 で変更: この関数は、 Android 以外では現在のロケールエンコーディングを surrogateescape エラーハンドラで使うようになりました。 以前は、 Py_EncodeLocale()surrogateescape で使われ、現在のロケールエンコーディングは strict で使われていました。

ファイルシステムエンコーディング

ファイル名や他の環境文字列のエンコードやデコードを行うには、 Py_FileSystemDefaultEncoding をエンコーディングとして使い、 Py_FileSystemDefaultEncodeErrors をエラーハンドラとして使うべきです (PEP 383 および PEP 529)。 引数の構文解析中にファイル名を bytes にエンコードするには、 "O&" コンバーターを使い、 PyUnicode_FSConverter() を変換関数として渡すべきです:

int PyUnicode_FSConverter(PyObject *obj, void *result)
Part of the Stable ABI.

ParseTuple converter: encode str objects -- obtained directly or through the os.PathLike interface -- to bytes using PyUnicode_EncodeFSDefault(); bytes objects are output as-is. result must be a PyBytesObject* which must be released when it is no longer used.

バージョン 3.1 で追加.

バージョン 3.6 で変更: path-like object を受け入れるようになりました。

引数の構文解析中にファイル名を str にデコードするには、 "O&" コンバーターを使い、 PyUnicode_FSDecoder() を変換関数として渡すのがよいです:

int PyUnicode_FSDecoder(PyObject *obj, void *result)
Part of the Stable ABI.

ParseTuple converter: decode bytes objects -- obtained either directly or indirectly through the os.PathLike interface -- to str using PyUnicode_DecodeFSDefaultAndSize(); str objects are output as-is. result must be a PyUnicodeObject* which must be released when it is no longer used.

バージョン 3.2 で追加.

バージョン 3.6 で変更: path-like object を受け入れるようになりました。

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

Decode a string from the filesystem encoding and error handler.

Py_FileSystemDefaultEncoding が設定されていない場合は、ロケールエンコーディングに差し戻されます。

Py_FileSystemDefaultEncoding は起動時にロケールエンコーディングで初期化され、それ以降は変更できません。 現在のロケールエンコーディングで文字列をデコードする必要がある場合は、 PyUnicode_DecodeLocaleAndSize() を使ってください。

参考

Py_DecodeLocale() 関数。

バージョン 3.6 で変更: Py_FileSystemDefaultEncodeErrors エラーハンドラを使うようになりました。

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

Decode a null-terminated string from the filesystem encoding and error handler.

Py_FileSystemDefaultEncoding が設定されていない場合は、ロケールエンコーディングに差し戻されます。

文字列の長さが分かっている場合は、 PyUnicode_DecodeFSDefaultAndSize() を使ってください。

バージョン 3.6 で変更: Py_FileSystemDefaultEncodeErrors エラーハンドラを使うようになりました。

PyObject *PyUnicode_EncodeFSDefault(PyObject *unicode)
Return value: New reference. Part of the Stable ABI.

Py_FileSystemDefaultEncoding エラーハンドラで Unicode オブジェクトを Py_FileSystemDefaultEncoding にエンコードし、 bytes を返します。 返される bytes オブジェクトは null バイトを含んでいるかもしれないことに注意してください。

Py_FileSystemDefaultEncoding が設定されていない場合は、ロケールエンコーディングに差し戻されます。

Py_FileSystemDefaultEncoding は起動時にロケールエンコーディングで初期化され、それ以降は変更できません。 現在のロケールエンコーディングで文字列をエンコードする必要がある場合は、 PyUnicode_EncodeLocale() を使ってください。

参考

Py_EncodeLocale() 関数。

バージョン 3.2 で追加.

バージョン 3.6 で変更: Py_FileSystemDefaultEncodeErrors エラーハンドラを使うようになりました。

wchar_t サポート

wchar_t support for platforms which support it:

PyObject *PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
Return value: New reference. Part of the Stable ABI.

Create a Unicode object from the wchar_t buffer w of the given size. Passing -1 as the size indicates that the function must itself compute the length, using wcslen. Return NULL on failure.

Py_ssize_t PyUnicode_AsWideChar(PyObject *unicode, wchar_t *w, Py_ssize_t size)
Part of the Stable ABI.

Copy the Unicode object contents into the wchar_t buffer w. At most size wchar_t characters are copied (excluding a possibly trailing null termination character). Return the number of wchar_t characters copied or -1 in case of an error. Note that the resulting wchar_t* string may or may not be null-terminated. It is the responsibility of the caller to make sure that the wchar_t* string is null-terminated in case this is required by the application. Also, note that the wchar_t* string might contain null characters, which would cause the string to be truncated when used with most C functions.

wchar_t *PyUnicode_AsWideCharString(PyObject *unicode, Py_ssize_t *size)
Part of the Stable ABI since version 3.7.

Convert the Unicode object to a wide character string. The output string always ends with a null character. If size is not NULL, write the number of wide characters (excluding the trailing null termination character) into *size. Note that the resulting wchar_t string might contain null characters, which would cause the string to be truncated when used with most C functions. If size is NULL and the wchar_t* string contains null characters a ValueError is raised.

Returns a buffer allocated by PyMem_Alloc() (use PyMem_Free() to free it) on success. On error, returns NULL and *size is undefined. Raises a MemoryError if memory allocation is failed.

バージョン 3.2 で追加.

バージョン 3.7 で変更: Raises a ValueError if size is NULL and the wchar_t* string contains null characters.

組み込み codec (built-in codec)

Python には、処理速度を高めるために C で書かれた codec が揃えてあります。これら全ての codec は以下の関数を介して直接利用できます。

以下の API の多くが、 encodingerrors という二つの引数をとります。これらのパラメータは、組み込みの文字列コンストラクタである str() における同名のパラメータと同じ意味を持ちます。

encodingNULL にすると、デフォルトエンコーディングである UTF-8 を使います。 ファイルシステムに関する関数の呼び出しでは、ファイル名に対するエンコーディングとして PyUnicode_FSConverter() を使わねばなりません。 これは内部で変数 Py_FileSystemDefaultEncoding を使用しています。 この変数は読み出し専用の変数として扱わねばなりません: この変数は、あるシステムによっては静的な文字列に対するポインタであったり、また別のシステムでは、(アプリケーションが setlocale を呼んだときなどに) 変わったりもします。

errors で指定するエラー処理もまた、 NULL を指定できます。 NULL を指定すると、codec で定義されているデフォルト処理の使用を意味します。全ての組み込み codec で、デフォルトのエラー処理は "strict" (ValueError を送出する) になっています。

個々の codec は全て同様のインターフェースを使っています。個別の codec の説明では、説明を簡単にするために以下の汎用のインターフェースとの違いだけを説明しています。

汎用 codec

以下は汎用 codec の API です:

PyObject *PyUnicode_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors)
Return value: New reference. Part of the Stable ABI.

size バイトのエンコードされた文字列 s をデコードして Unicode オブジェクトを生成します。 encodingerrors は、組み込み関数 str() の同名のパラメータと同じ意味を持ちます。 使用する codec の検索は、 Python の codec レジストリを使って行います。 codec が例外を送出した場合には NULL を返します。

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

Unicode オブジェクトをエンコードし、その結果を Python の bytes オブジェクトとして返します。 encoding および errors は Unicode 型の encode() メソッドに与える同名のパラメータと同じ意味を持ちます。 使用する codec の検索は、 Python の codec レジストリを使って行います。 codec が例外を送出した場合には NULL を返します。

PyObject *PyUnicode_Encode(const Py_UNICODE *s, Py_ssize_t size, const char *encoding, const char *errors)
Return value: New reference.

size で指定されたサイズの Py_UNICODE バッファ s をエンコードした Python の bytes オブジェクトを返します。 encoding および errors は Unicode 型の encode() メソッドに与える同名のパラメータと同じ意味を持ちます。 使用する codec の検索は、 Python の codec レジストリを使って行います。 codec が例外を送出した場合には NULL を返します。

バージョン 3.3 で非推奨、バージョン 3.11 で削除予定: 古いスタイルの Py_UNICODE APIの一部です; PyUnicode_AsEncodedString() を使用するように移行してください。

UTF-8 Codecs

以下は UTF-8 codec の APIです:

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

UTF-8 でエンコードされた size バイトの文字列 s から Unicode オブジェクトを生成します。codec が例外を送出した場合には NULL を返します。

PyObject *PyUnicode_DecodeUTF8Stateful(const char *s, Py_ssize_t size, const char *errors, Py_ssize_t *consumed)
Return value: New reference. Part of the Stable ABI.

consumedNULL の場合、 PyUnicode_DecodeUTF8() と同じように動作します。 consumedNULL でない場合、末尾の不完全な UTF-8 バイト列はエラーとみなされません。これらのバイト列はデコードされず、デコードされたバイト数は consumed に格納されます。

PyObject *PyUnicode_AsUTF8String(PyObject *unicode)
Return value: New reference. Part of the Stable ABI.

UTF-8 で Unicode オブジェクトをエンコードし、結果を Python バイト列オブジェクトとして返します。エラー処理は "strict" です。 codec が例外を送出した場合には NULL を返します。

const char *PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *size)
Part of the Stable ABI since version 3.10.

Unicode オブジェクトを UTF-8 でエンコードしたものへのポインタを返し、エンコードされた表現形式でのサイズ (バイト単位) を size に格納します。 size 引数は NULL でも構いません; その場合はサイズは格納されません。 返されるバッファには、 null コードポイントがあるかどうかに関わらず、常に null バイトが終端に付加されています (これは size には勘定されません)。

エラーが起きた場合は、 NULL を返し、例外を設定し、 size には何も格納しません。

This caches the UTF-8 representation of the string in the Unicode object, and subsequent calls will return a pointer to the same buffer. The caller is not responsible for deallocating the buffer. The buffer is deallocated and pointers to it become invalid when the Unicode object is garbage collected.

バージョン 3.3 で追加.

バージョン 3.7 で変更: 返り値の型が char * ではなく const char * になりました。

バージョン 3.10 で変更: This function is a part of the limited API.

const char *PyUnicode_AsUTF8(PyObject *unicode)

PyUnicode_AsUTF8AndSize() とほぼ同じですが、サイズを格納しません。

バージョン 3.3 で追加.

バージョン 3.7 で変更: 返り値の型が char * ではなく const char * になりました。

PyObject *PyUnicode_EncodeUTF8(const Py_UNICODE *s, Py_ssize_t size, const char *errors)
Return value: New reference.

与えられたサイズの Py_UNICODE バッファ s を UTF-8 でエンコードして、 Python の bytes オブジェクトとして返します。 codec が例外を発生させたときは NULL を返します。

バージョン 3.3 で非推奨、バージョン 3.11 で削除予定: 古いスタイルの Py_UNICODE APIの一部です; PyUnicode_AsUTF8String(), PyUnicode_AsUTF8AndSize(), PyUnicode_AsEncodedString() のいずれかを使用するように移行してください。

UTF-32 Codecs

以下は UTF-32 codec API です:

PyObject *PyUnicode_DecodeUTF32(const char *s, Py_ssize_t size, const char *errors, int *byteorder)
Return value: New reference. Part of the Stable ABI.

UTF-32 でエンコードされたバッファ文字列から size バイトをデコードし、 Unicodeオブジェクトとして返します。 errors は (NULL でないなら) エラーハンドラを指定します。デフォルトは "strict" です。

byteorderNULL でない時、デコーダは与えられたバイトオーダーでデコードを開始します。

*byteorder == -1: little endian
*byteorder == 0:  native order
*byteorder == 1:  big endian

*byteorder が 0 で、入力データの最初の 4 バイトが byte order mark (BOM) ならば、デコーダはこのバイトオーダーに切り替え、BOM は結果の Unicode 文字列にコピーされません。 *byteorder-1 または 1 ならば、全ての byte order mark は出力にコピーされます。

デコードが完了した後、入力データの終端に来た時点でのバイトオーダーを *byteorder にセットします。

byteorderNULL のとき、 codec は native order モードで開始します。

codec が例外を発生させたときは NULL を返します。

PyObject *PyUnicode_DecodeUTF32Stateful(const char *s, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed)
Return value: New reference. Part of the Stable ABI.

consumedNULL のとき、 PyUnicode_DecodeUTF32() と同じように振る舞います。 consumedNULL でないとき、 PyUnicode_DecodeUTF32Stateful() は末尾の不完全な (4 で割り切れない長さのバイト列などの) UTF-32 バイト列をエラーとして扱いません。末尾の不完全なバイト列はデコードされず、デコードされたバイト数が consumed に格納されます。

PyObject *PyUnicode_AsUTF32String(PyObject *unicode)
Return value: New reference. Part of the Stable ABI.

ネイティブバイトオーダーで UTF-32 エンコーディングされた Python バイト文字列を返します。 文字列は常に BOM マークで始まります。 エラーハンドラは "strict" です。 codec が例外を発生させたときは NULL を返します。

PyObject *PyUnicode_EncodeUTF32(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder)
Return value: New reference.

s の Unicode データを UTF-32 にエンコードし、その値を Python の bytes オブジェクトに格納して返します。 出力は以下のバイトオーダーで従って書かれます:

byteorder == -1: little endian
byteorder == 0:  native byte order (writes a BOM mark)
byteorder == 1:  big endian

byteorder が 0 のとき、出力文字列は常に Unicode BOM マーク (U+FEFF) で始まります。それ以外の2つのモードでは、先頭に BOM マークは出力されません。

If Py_UNICODE_WIDE is not defined, surrogate pairs will be output as a single code point.

codec が例外を発生させたときは NULL を返します。

バージョン 3.3 で非推奨、バージョン 3.11 で削除予定: 古いスタイルの Py_UNICODE APIの一部です; PyUnicode_AsUTF32String() または PyUnicode_AsEncodedString() を使用するように移行してください。

UTF-16 Codecs

以下は UTF-16 codec の APIです:

PyObject *PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors, int *byteorder)
Return value: New reference. Part of the Stable ABI.

UTF-16 でエンコードされたバッファ s から size バイトだけデコードして、結果を Unicode オブジェクトで返します。 errors は (NULL でない場合) エラー処理方法を定義します。デフォルト値は "strict" です。

byteorderNULL でない時、デコーダは与えられたバイトオーダーでデコードを開始します。

*byteorder == -1: little endian
*byteorder == 0:  native order
*byteorder == 1:  big endian

*byteorder が 0 で、入力データの先頭2バイトがバイトオーダーマーク (BOM) だった場合、デコーダは BOM が示すバイトオーダーに切り替え、そのBOMを結果の Unicode 文字列にコピーしません。 *byteorder-11 だった場合、すべてのBOMは出力へコピーされます (出力では \ufeff\ufffe のどちらかになるでしょう)。

デコードが完了した後、入力データの終端に来た時点でのバイトオーダーを *byteorder にセットします。

byteorderNULL のとき、 codec は native order モードで開始します。

codec が例外を発生させたときは NULL を返します。

PyObject *PyUnicode_DecodeUTF16Stateful(const char *s, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed)
Return value: New reference. Part of the Stable ABI.

consumedNULL の場合、 PyUnicode_DecodeUTF16() と同じように動作します。 consumedNULL でない場合、 PyUnicode_DecodeUTF16Stateful() は末尾の不完全な UTF-16 バイト列 (奇数長のバイト列や分割されたサロゲートペア) をエラーとみなしません。これらのバイト列はデコードされず、デコードされたバイト数を consumed に返します。

PyObject *PyUnicode_AsUTF16String(PyObject *unicode)
Return value: New reference. Part of the Stable ABI.

ネイティブバイトオーダーで UTF-16 エンコーディングされた Python バイト文字列を返します。 文字列は常に BOM マークで始まります。 エラーハンドラは "strict" です。 codec が例外を発生させたときは NULL を返します。

PyObject *PyUnicode_EncodeUTF16(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder)
Return value: New reference.

s の Unicode データを UTF-16 にエンコードし、その値を Python の bytes オブジェクトに格納して返します。 出力は以下のバイトオーダーに従って書かれます:

byteorder == -1: little endian
byteorder == 0:  native byte order (writes a BOM mark)
byteorder == 1:  big endian

byteorder が 0 のとき、出力文字列は常に Unicode BOM マーク (U+FEFF) で始まります。それ以外の2つのモードでは、先頭に BOM マークは出力されません。

If Py_UNICODE_WIDE is defined, a single Py_UNICODE value may get represented as a surrogate pair. If it is not defined, each Py_UNICODE values is interpreted as a UCS-2 character.

codec が例外を発生させたときは NULL を返します。

バージョン 3.3 で非推奨、バージョン 3.11 で削除予定: 古いスタイルの Py_UNICODE APIの一部です; PyUnicode_AsUTF16String() または PyUnicode_AsEncodedString() を使用するように移行してください。

UTF-7 Codecs

以下は UTF-7 codec の API です:

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

UTF-7 でエンコードされた size バイトの文字列 s をデコードして Unicode オブジェクトを作成します。 codec が例外を発生させたときは NULL を返します。

PyObject *PyUnicode_DecodeUTF7Stateful(const char *s, Py_ssize_t size, const char *errors, Py_ssize_t *consumed)
Return value: New reference. Part of the Stable ABI.

consumedNULL のとき、 PyUnicode_DecodeUTF7() と同じように動作します。 consumedNULL でないとき、末尾の不完全な UTF-7 base-64 部分をエラーとしません。不完全な部分のバイト列はデコードせずに、デコードしたバイト数を consumed に格納します。

PyObject *PyUnicode_EncodeUTF7(const Py_UNICODE *s, Py_ssize_t size, int base64SetO, int base64WhiteSpace, const char *errors)
Return value: New reference.

与えられたサイズの Py_UNICODE バッファを UTF-7 でエンコードして、 Python の bytes オブジェクトとして返します。 codec が例外を発生させたときは NULL を返します。

base64SetO がゼロでないとき、 "Set O" 文字 (他の場合には何も特別な意味を持たない句読点) を base-64 エンコードします。 base64WhiteSpace がゼロでないとき、空白文字を base-64 エンコードします。 Python の "utf-7" codec では、両方ともゼロに設定されています。

バージョン 3.3 で非推奨、バージョン 3.11 で削除予定: 古いスタイルの Py_UNICODE APIの一部です; PyUnicode_AsEncodedString() を使用するように移行してください。

Unicode-Escape Codecs

以下は "Unicode Escape" codec の API です:

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

Unicode-Escape でエンコードされた size バイトの文字列 s から Unicode オブジェクトを生成します。codec が例外を送出した場合には NULL を返します。

PyObject *PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Return value: New reference. Part of the Stable ABI.

Unicode-Escape を使い Unicode オブジェクトをエンコードし、結果を bytes オブジェクトとして返します。 エラー処理は "strict" です。 codec が例外を送出した場合には NULL を返します。

PyObject *PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size)
Return value: New reference.

Unicode-Escape を使い size で指定された長さを持つ Py_UNICODE 型バッファをエンコードし、 bytes オブジェクトにして返します。 codec が例外を送出した場合には NULL を返します。

バージョン 3.3 で非推奨、バージョン 3.11 で削除予定: 古いスタイルの Py_UNICODE APIの一部です; PyUnicode_AsUnicodeEscapeString() を使用するように移行してください。

Raw-Unicode-Escape Codecs

以下は "Raw Unicode Escape" codec の APIです:

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

Raw-Unicode-Escape でエンコードされた size バイトの文字列 s から Unicode オブジェクトを生成します。codec が例外を送出した場合には NULL を返します。

PyObject *PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Return value: New reference. Part of the Stable ABI.

Raw-Unicode-Escape を使い Unicode オブジェクトをエンコードし、結果を bytes オブジェクトとして返します。 エラー処理は "strict" です。 codec が例外を送出した場合には NULL を返します。

PyObject *PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size)
Return value: New reference.

Raw-Unicode-Escape を使い size で指定された長さを持つ Py_UNICODE 型バッファをエンコードし、 bytes オブジェクトにして返します。 codec が例外を送出した場合には NULL を返します。

バージョン 3.3 で非推奨、バージョン 3.11 で削除予定: 古いスタイルの Py_UNICODE APIの一部です; PyUnicode_AsRawUnicodeEscapeString() または PyUnicode_AsEncodedString() を使用するように移行してください。

Latin-1 Codecs

以下は Latin-1 codec の APIです: Latin-1 は、 Unicode 序数の最初の 256 個に対応し、エンコード時にはこの 256 個だけを受理します。

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

Latin-1 でエンコードされた size バイトの文字列 s から Unicode オブジェクトを生成します。codec が例外を送出した場合には NULL を返します。

PyObject *PyUnicode_AsLatin1String(PyObject *unicode)
Return value: New reference. Part of the Stable ABI.

Latin-1 で Unicode オブジェクトをエンコードし、結果を Python bytes オブジェクトとして返します。 エラー処理は "strict" です。 codec が例外を送出した場合には NULL を返します。

PyObject *PyUnicode_EncodeLatin1(const Py_UNICODE *s, Py_ssize_t size, const char *errors)
Return value: New reference.

size で指定された長さを持つ Py_UNICODE 型バッファを Latin-1 でエンコードし、 Python bytes オブジェクトにして返します。 codec が例外を送出した場合には NULL を返します。

バージョン 3.3 で非推奨、バージョン 3.11 で削除予定: 古いスタイルの Py_UNICODE APIの一部です; PyUnicode_AsLatin1String() または PyUnicode_AsEncodedString() を使用するように移行してください。

ASCII Codecs

以下は ASCII codec の APIです。 7 ビットの ASCII データだけを受理します。その他のコードはエラーになります。

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

ASCII でエンコードされた size バイトの文字列 s から Unicode オブジェクトを生成します。codec が例外を送出した場合には NULL を返します。

PyObject *PyUnicode_AsASCIIString(PyObject *unicode)
Return value: New reference. Part of the Stable ABI.

ASCII で Unicode オブジェクトをエンコードし、結果を Python bytes オブジェクトとして返します。 エラー処理は "strict" です。 codec が例外を送出した場合には NULL を返します。

PyObject *PyUnicode_EncodeASCII(const Py_UNICODE *s, Py_ssize_t size, const char *errors)
Return value: New reference.

size で指定された長さを持つ Py_UNICODE 型バッファを ASCII でエンコードし、 Python bytes オブジェクトにして返します。 codec が例外を送出した場合には NULL を返します。

バージョン 3.3 で非推奨、バージョン 3.11 で削除予定: 古いスタイルの Py_UNICODE APIの一部です; PyUnicode_AsASCIIString() または PyUnicode_AsEncodedString() を使用するように移行してください。

Character Map Codecs

この codec は、多くの様々な codec を実装する際に使われるという点で特殊な codec です (実際、 encodings パッケージに入っている標準 codecs のほとんどは、この codec を使っています)。 この codec は、文字のエンコードやデコードに対応表を使います。 提供される対応表のオブジェクトは __getitem__() マッピングインターフェースをサポートしていなければなりません; 辞書やシーケンスがそれに適しています。

以下は mapping codec の APIです:

PyObject *PyUnicode_DecodeCharmap(const char *data, Py_ssize_t size, PyObject *mapping, const char *errors)
Return value: New reference. Part of the Stable ABI.

与えられた mapping オブジェクトを使って、 size バイトのエンコードされた文字列 s をデコードして Unicode オブジェクトを作成します。 codec が例外を発生させたときは NULL を返します。

If mapping is NULL, Latin-1 decoding will be applied. Else mapping must map bytes ordinals (integers in the range from 0 to 255) to Unicode strings, integers (which are then interpreted as Unicode ordinals) or None. Unmapped data bytes -- ones which cause a LookupError, as well as ones which get mapped to None, 0xFFFE or '\ufffe', are treated as undefined mappings and cause an error.

PyObject *PyUnicode_AsCharmapString(PyObject *unicode, PyObject *mapping)
Return value: New reference. Part of the Stable ABI.

Unicode オブジェクトを mapping に指定されたオブジェクトを使ってエンコードし、結果を bytes オブジェクトとして返します。エラー処理は "strict" です。 codec が例外を送出した場合には NULL を返します。

The mapping object must map Unicode ordinal integers to bytes objects, integers in the range from 0 to 255 or None. Unmapped character ordinals (ones which cause a LookupError) as well as mapped to None are treated as "undefined mapping" and cause an error.

PyObject *PyUnicode_EncodeCharmap(const Py_UNICODE *s, Py_ssize_t size, PyObject *mapping, const char *errors)
Return value: New reference.

Encode the Py_UNICODE buffer of the given size using the given mapping object and return the result as a bytes object. Return NULL if an exception was raised by the codec.

バージョン 3.3 で非推奨、バージョン 3.11 で削除予定: 古いスタイルの Py_UNICODE APIの一部です; PyUnicode_AsCharmapString() または PyUnicode_AsEncodedString() を使用するように移行してください。

以下の codec API は Unicode から Unicode への対応付けを行う特殊なものです。

PyObject *PyUnicode_Translate(PyObject *str, PyObject *table, const char *errors)
Return value: New reference. Part of the Stable ABI.

文字列に文字対応表 table を適用して変換し、変換結果を Unicode オブジェクトで返します。codec が例外を発行した場合には NULL を返します。

対応表は、Unicode 序数を表す整数を Unicode 序数を表す整数または None (その文字を削除する) に対応付けなければなりません。

対応表が提供する必要があるメソッドは __getitem__() インターフェースだけです; 従って、辞書やシーケンス型を使ってもうまく動作します。 対応付けを行っていない (LookupError を起こすような) 文字序数に対しては、変換は行わず、そのままコピーします。

errors は codecs で通常使われるのと同じ意味を持ちます。 errorsNULL にしてもよく、デフォルトエラー処理の使用を意味します。

PyObject *PyUnicode_TranslateCharmap(const Py_UNICODE *s, Py_ssize_t size, PyObject *mapping, const char *errors)
Return value: New reference.

Translate a Py_UNICODE buffer of the given size by applying a character mapping table to it and return the resulting Unicode object. Return NULL when an exception was raised by the codec.

バージョン 3.3 で非推奨、バージョン 3.11 で削除予定: 古いスタイルの Py_UNICODE APIの一部です; PyUnicode_Translate(). または 汎用の codec ベースの API を使用するように移行してください。

Windows 用の MBCS codec

以下は MBCS codec の API です。この codec は現在のところ、 Windows 上だけで利用でき、変換の実装には Win32 MBCS 変換機構 (Win32 MBCS converter) を使っています。 MBCS (または DBCS) はエンコード方式の種類 (class) を表す言葉で、単一のエンコード方式を表すわけでなないので注意してください。利用されるエンコード方式 (target encoding) は、 codec を動作させているマシン上のユーザ設定で定義されています。

PyObject *PyUnicode_DecodeMBCS(const char *s, Py_ssize_t size, const char *errors)
Return value: New reference. Part of the Stable ABI on Windows since version 3.7.

MBCS でエンコードされた size バイトの文字列 s から Unicode オブジェクトを生成します。codec が例外を送出した場合には NULL を返します。

PyObject *PyUnicode_DecodeMBCSStateful(const char *s, Py_ssize_t size, const char *errors, Py_ssize_t *consumed)
Return value: New reference. Part of the Stable ABI on Windows since version 3.7.

consumedNULL のとき、 PyUnicode_DecodeMBCS() と同じ動作をします。 consumedNULL でないとき、 PyUnicode_DecodeMBCSStateful() は文字列の最後にあるマルチバイト文字の前半バイトをデコードせず、 consumed にデコードしたバイト数を格納します。

PyObject *PyUnicode_AsMBCSString(PyObject *unicode)
Return value: New reference. Part of the Stable ABI on Windows since version 3.7.

MBCS で Unicode オブジェクトをエンコードし、結果を Python バイト列オブジェクトとして返します。エラー処理は "strict" です。 codec が例外を送出した場合には NULL を返します。

PyObject *PyUnicode_EncodeCodePage(int code_page, PyObject *unicode, const char *errors)
Return value: New reference. Part of the Stable ABI on Windows since version 3.7.

指定されたコードページを使い Unicode オブジェクトをエンコードし、 Python bytes オブジェクトを返します。 codec が例外を送出した場合には NULL を返します。 CP_ACP コードページを使い MBCS エンコーダを取得してください。

バージョン 3.3 で追加.

PyObject *PyUnicode_EncodeMBCS(const Py_UNICODE *s, Py_ssize_t size, const char *errors)
Return value: New reference.

size で指定された長さを持つ Py_UNICODE 型バッファを MBCS でエンコードし、 Python bytes オブジェクトにして返します。 codec が例外を送出した場合には NULL を返します。

バージョン 3.3 で非推奨、バージョン 4.0 で削除予定: 古いスタイルの Py_UNICODE APIの一部です; PyUnicode_AsMBCSString(), PyUnicode_EncodeCodePage(), PyUnicode_AsEncodedString() のいずれかを使用するように移行してください。

メソッドとスロット

メソッドおよびスロット関数 (slot function)

以下の API は Unicode オブジェクトおよび文字列を入力に取り (説明では、どちらも文字列と表記しています)、場合に応じて Unicode オブジェクトか整数を返す機能を持っています。

これらの関数は全て、例外が発生した場合には NULL または -1 を返します。

PyObject *PyUnicode_Concat(PyObject *left, PyObject *right)
Return value: New reference. Part of the Stable ABI.

二つの文字列を結合して、新たな Unicode 文字列を生成します。

PyObject *PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Return value: New reference. Part of the Stable ABI.

Unicode 文字列のリストを分割して、 Unicode 文字列からなるリストを返します。 sepNULL の場合、全ての空白文字を使って分割を行います。それ以外の場合、指定された文字を使って分割を行います。最大で maxsplit 個までの分割を行います。 maxsplit が負ならば分割数に制限を設けません。分割結果のリスト内には分割文字は含みません。

PyObject *PyUnicode_Splitlines(PyObject *s, int keepend)
Return value: New reference. Part of the Stable ABI.

Unicode 文字列を改行文字で区切り、Unicode 文字列からなるリストを返します。 CRLF は一個の改行文字とみなします。 keepend0 の場合、分割結果のリスト内に改行文字を含めません。

PyObject *PyUnicode_Join(PyObject *separator, PyObject *seq)
Return value: New reference. Part of the Stable ABI.

指定した separator で文字列からなるシーケンスを連結 (join) し、連結結果を Unicode 文字列で返します。

Py_ssize_t PyUnicode_Tailmatch(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction)
Part of the Stable ABI.

substrstr[start:end] の末端 (direction == -1 は先頭一致、 direction == 1 は末尾一致) でとマッチする場合に 1 を返し、それ以外の場合には 0 を返します。 エラーが発生した時は -1 を返します。

Py_ssize_t PyUnicode_Find(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction)
Part of the Stable ABI.

str[start:end] 中に substr が最初に出現する場所を返します。 このとき指定された検索方向 direction (direction == 1 は順方向検索、 direction == -1 は逆方向検索) で検索します。 戻り値は最初にマッチが見つかった場所のインデックスです; 戻り値 -1 はマッチが見つからなかったことを表し、 -2 はエラーが発生して例外情報が設定されていることを表します。

Py_ssize_t PyUnicode_FindChar(PyObject *str, Py_UCS4 ch, Py_ssize_t start, Py_ssize_t end, int direction)
Part of the Stable ABI since version 3.7.

str[start:end] 中に文字 ch が最初に出現する場所を返します。 このとき指定された検索方向 direction (direction == 1 は順方向検索、 direction == -1 は逆方向検索) で検索します。 戻り値は最初にマッチが見つかった場所のインデックスです; 戻り値 -1 はマッチが見つからなかったことを表し、 -2 はエラーが発生して例外情報が設定されていることを表します。

バージョン 3.3 で追加.

バージョン 3.7 で変更: start and end are now adjusted to behave like str[start:end].

Py_ssize_t PyUnicode_Count(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end)
Part of the Stable ABI.

str[start:end]substr が重複することなく出現する回数を返します。エラーが発生した場合には -1 を返します。

PyObject *PyUnicode_Replace(PyObject *str, PyObject *substr, PyObject *replstr, Py_ssize_t maxcount)
Return value: New reference. Part of the Stable ABI.

str 中に出現する substr を最大で maxcountreplstr に置換し、置換結果である Unicode オブジェクトを返します。 maxcount == -1 にすると、文字列中に現れる全ての substr を置換します。

int PyUnicode_Compare(PyObject *left, PyObject *right)
Part of the Stable ABI.

二つの文字列を比較して、左引数が右引数より小さい場合、左右引数が等価の場合、左引数が右引数より大きい場合に対して、それぞれ -1, 0, 1 を返します。

この関数は、失敗したときに -1 を返すので、 PyErr_Occurred() を呼び出して、エラーをチェックすべきです。

int PyUnicode_CompareWithASCIIString(PyObject *uni, const char *string)
Part of the Stable ABI.

Unicode オブジェクト unistring を比較して、左引数が右引数より小さい場合、左右引数が等価の場合、左引数が右引数より大きい場合に対して、それぞれ -1, 0, 1 を返します。 ASCII エンコードされた文字列だけを渡すのが最も良いですが、入力文字列に非 ASCII 文字が含まれている場合は ISO-8859-1 として解釈します。

この関数は例外を送出しません。

PyObject *PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Return value: New reference. Part of the Stable ABI.

二つのUnicode文字列を比較して、下のうちの一つを返します:

  • NULL を、例外が発生したときに返します。

  • Py_True もしくは Py_False を、正しく比較できた時に返します。

  • Py_NotImplemented を、 leftright のどちらかに対する PyUnicode_FromObject() が失敗したときに返します。(原文: in case the type combination is unknown)

op に入れられる値は、 Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, and Py_LE のどれかです。

PyObject *PyUnicode_Format(PyObject *format, PyObject *args)
Return value: New reference. Part of the Stable ABI.

新たな文字列オブジェクトを format および args から生成して返します; このメソッドは format % args のようなものです。

int PyUnicode_Contains(PyObject *container, PyObject *element)
Part of the Stable ABI.

elementcontainer 内にあるか調べ、その結果に応じて真または偽を返します。

element は単要素の Unicode 文字に型強制できなければなりません。エラーが生じた場合には -1 を返します。

void PyUnicode_InternInPlace(PyObject **string)
Part of the Stable ABI.

Intern the argument *string in place. The argument must be the address of a pointer variable pointing to a Python Unicode string object. If there is an existing interned string that is the same as *string, it sets *string to it (releasing the reference to the old string object and creating a new strong reference to the interned string object), otherwise it leaves *string alone and interns it (creating a new strong reference). (Clarification: even though there is a lot of talk about references, think of this function as reference-neutral; you own the object after the call if and only if you owned it before the call.)

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

PyUnicode_FromString()PyUnicode_InternInPlace() を組み合わせたもので、収容済みの新たな文字列オブジェクトを返すか、同じ値を持つ収容済みの Unicode 文字列オブジェクトに対する新たな ("所有権のある") 参照を返します。