Search This Blog

Labels

Friday, December 17, 2010

《扩展和嵌入Python解释器(译稿)》1.9 Building Arbitrary Values 构建任意值

This function is the counterpart to PyArg_ParseTuple(). It is declared as follows:

与PyArg_ParseTuple()相对应的函数以下面的方式声明:

PyObject *Py_BuildValue(char *format, …);

It recognizes a set of format units similar to the ones recognized by PyArg_ParseTuple(), but the arguments (which are input to the function, not output) must not be pointers, just values. It returns a new Python object, suitable for returning from a C function called from Python.

类似于PyArg_ParseTuple()函数,该函数识别一系列格式单元,但参数(函数的输入,不是输出)不能是指针,只能是值。它返回一个新的Python 对象,适合于从Python中调用C函数时作为函数的返回值

One difference with PyArg_ParseTuple(): while the latter requires its first argument to be a tuple (since Python argument lists are always represented as tuples internally),Py_BuildValue()does not always build a tuple. It builds a tuple only if its format string contains two or more format units. If the format string is empty, it returns None; if it contains exactly one format unit, it returns whatever object is described by that format unit. To force it to return a tuple of size 0 or one, parenthesize the format string.

同PyArg_ParseTuple()的一个区别是:后者要求其第一个参数为元组(由于Python参数列表在Python内部总是被描述成元组),而Py_BuildValue()并非总是创建一个元组。仅当其格式字符串包含两个或两个以上的格式单元时返回元组。若格式字符串为空,则返回None;若恰只含一个格式单元,则返回由格式字符串描述的任意对象。要强制返回大小为 0 或 1 的元组就要将格式字符串用括号括起来。

Examples (to the left the call, to the right the resulting Python value):

一些例子(左为函数调用,右为创建的Python值)

Py_BuildValue("")                        None

Py_BuildValue("i", 123)                 123

Py_BuildValue("iii", 123, 456, 789)   (123, 456, 789)

Py_BuildValue("s", "hello")             ’hello’

Py_BuildValue("ss", "hello", "world") (’hello’, ’world’)

Py_BuildValue("s#", "hello", 4)        ’hell’

Py_BuildValue("()")                       ()

Py_BuildValue("(i)", 123)                (123,)

Py_BuildValue("(ii)", 123, 456)         (123, 456)

Py_BuildValue("(i,i)", 123, 456)        (123, 456)

Py_BuildValue("[i,i]", 123, 456)        [123, 456]

Py_BuildValue("{s:i,s:i}",

"abc", 123, "def", 456)  {’abc’: 123, ’def’: 456}

Py_BuildValue("((ii)(ii)) (ii)",

1, 2, 3, 4, 5, 6)         (((1, 2), (3, 4)), (5, 6))

No comments:

Post a Comment