python / python/cpython

`_objects` attribute of ctypes data instances is sometimes not None or a dictionary

Open
#132,177 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

docs topic-ctypes
Dominant language
Python
Stars
77.2k
Forks
36k
PR merge metrics
PR metrics pending

Description

Documentation

According to the current ctypes docs, the _objects attribute of ctypes data instances is supposed to be either None or a dictionary:

_objects
This member is either None or a dictionary containing Python objects that need to be kept alive so that the memory block contents is kept valid. This object is only exposed for debugging; never modify the contents of this dictionary.

However, instances created with from_buffer have this attribute set to a memoryview of the source buffer, not to a dictionary:

>>> import ctypes
>>> x = ctypes.c_uint8.from_buffer(bytearray(1), 0)
>>> type(x._objects)
<class 'memoryview'>

This behavior traces to this call of KeepRef inside CDataType_from_buffer_impl. Prior to this call, the result's b_objects is NULL, so this branch in KeepRef is taken, setting b_objects to reference the memoryview.

I'm not familiar with ctypes internals, but to my reading this behavior seems intentional and doesn't appear to cause any problems. Hence I'm filing this as a docs issue.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the _CData._objects documentation and the referenced CDataType_from_buffer_impl and KeepRef code in Modules/_ctypes/_ctypes.c. Confirm whether from_buffer's memoryview behavior is intentional, then update the documentation to accurately describe it; verify the documented behavior against the provided ctypes example.

Written by the indexing model from the issue text.

Assessment

Tech stack
c, python
Domain
documentation
Issue type
Documentation
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
52/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.