[Python-Dev] Py_SIZE vs PyXXX_GET_SIZE

Brett Cannon brett at python.org
Mon Mar 20 13:04:52 EDT 2017


On Mon, 20 Mar 2017 at 04:28 Serhiy Storchaka <storchaka at gmail.com> wrote:

> What is the preferable way of getting the size of tuple, list, bytes,
> bytearray: Py_SIZE or PyTuple_GET_SIZE, PyList_GET_SIZE,
> PyBytes_GET_SIZE, PyByteArray_GET_SIZE? Are macros for concrete types
> more preferable or they are outdated?
>
> On one hand concrete type macros are longer than Py_SIZE, and since
> concrete type macros are defined not for all PyVarObject types we need
> to use Py_SIZE for them in any case (for example for PyLongObject and
> PyTypeObject).
>
> On other hand we can add asserts for checking that concrete type macros
> are used with correct types. When I wrote a patch that replaces Py_SIZE
> with concrete type macros I found two cases of misusing Py_SIZE with
> dict object: one in _json.c (already fixed in
> 3023ebb43f7607584c3e123aff56e867cb04a418) and other in dictobject.c
> (still not fixed). If prefer using concrete type macros this would
> unlikely happen.
>

Personally I have always used the concrete versions when available when it
doesn't forcibly constrain the input to the function. In other words I
wouldn't force a function to only take a list so I could use
PyList_GET_SIZE, but if I'm constructing some internal list object or a
function is defined to return a list already then I would just use the
concrete versions. But I also wouldn't worry about changing uses of Py_SIZE
unless I was already changing the surrounding code.

I guess we could clarify this in PEP 7 if it doesn't say when to care about
this and once we reach consensus on what we all prefer.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20170320/313242f1/attachment.html>


More information about the Python-Dev mailing list