有用的宏

Python 头文件中定义了一些有用的宏。许多是在靠近它们被使用的地方定义的(例如 Py_RETURN_NONE)。其他更为通用的则定义在这里。这里所显示的并不是一个完整的列表。

Py_UNREACHABLE()

Use this when you have a code path that cannot be reached by design. For example, in the default: clause in a switch statement for which all possible values are covered in case statements. Use this in places where you might be tempted to put an assert(0) or abort() call.

In release mode, the macro helps the compiler to optimize the code, and avoids a warning about unreachable code. For example, the macro is implemented with __builtin_unreachable() on GCC in release mode.

A use for Py_UNREACHABLE() is following a call a function that never returns but that is not declared _Py_NO_RETURN.

If a code path is very unlikely code but can be reached under exceptional case, this macro must not be used. For example, under low memory condition or if a system call returns a value out of the expected range. In this case, it’s better to report the error to the caller. If the error cannot be reported to caller, Py_FatalError() can be used.

3.7 新版功能.

Py_ABS(x)

返回 x 的绝对值。

3.3 新版功能.

Py_MIN(x, y)

返回 xy 当中的最小值。

3.3 新版功能.

Py_MAX(x, y)

返回 xy 当中的最大值。

3.3 新版功能.

Py_STRINGIFY(x)

x 转换为 C 字符串。例如 Py_STRINGIFY(123) 返回 "123"

3.4 新版功能.

Py_MEMBER_SIZE(type, member)

返回结构 (type) member 的大小,以字节表示。

3.6 新版功能.

Py_CHARMASK(c)

参数必须为 [-128, 127] 或 [0, 255] 范围内的字符或整数类型。这个宏将 c 强制转换为 unsigned char 返回。

Py_GETENV(s)

Like getenv(s), but returns NULL if -E was passed on the command line (i.e. if Py_IgnoreEnvironmentFlag is set).

Py_UNUSED(arg)

Use this for unused arguments in a function definition to silence compiler warnings. Example: int func(int a, int Py_UNUSED(b)) { return a; }.

3.4 新版功能.

Py_DEPRECATED(version)

Use this for deprecated declarations. The macro must be placed before the symbol name.

示例:

  1. Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);

在 3.8 版更改: MSVC support was added.

PyDoc_STRVAR(name, str)

Creates a variable with name name that can be used in docstrings. If Python is built without docstrings, the value will be empty.

Use PyDoc_STRVAR for docstrings to support building Python without docstrings, as specified in PEP 7.

示例:

  1. PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
  2. static PyMethodDef deque_methods[] = {
  3. // ...
  4. {"pop", (PyCFunction)deque_pop, METH_NOARGS, pop_doc},
  5. // ...
  6. }

PyDoc_STR(str)

Creates a docstring for the given input string or an empty string if docstrings are disabled.

Use PyDoc_STR in specifying docstrings to support building Python without docstrings, as specified in PEP 7.

示例:

  1. static PyMethodDef pysqlite_row_methods[] = {
  2. {"keys", (PyCFunction)pysqlite_row_keys, METH_NOARGS,
  3. PyDoc_STR("Returns the keys of the row.")},
  4. {NULL, NULL}
  5. };