python / cpython

The Python programming language
https://www.python.org
Other
63.11k stars 30.22k forks source link

Should we re-export `PyObj_FromPtr` in `ctypes`? #90743

Open sobolevn opened 2 years ago

sobolevn commented 2 years ago
BPO 46585
Nosy @amauryfa, @abalkin, @meadori, @zware, @eryksun, @sobolevn

Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.

Show more details

GitHub fields: ```python assignee = None closed_at = None created_at = labels = ['ctypes', 'type-bug', '3.11'] title = 'Should we re-export `PyObj_FromPtr` in `ctypes`?' updated_at = user = 'https://github.com/sobolevn' ``` bugs.python.org fields: ```python activity = actor = 'eryksun' assignee = 'none' closed = False closed_date = None closer = None components = ['ctypes'] creation = creator = 'sobolevn' dependencies = [] files = [] hgrepos = [] issue_num = 46585 keywords = [] message_count = 2.0 messages = ['412155', '412165'] nosy_count = 6.0 nosy_names = ['amaury.forgeotdarc', 'belopolsky', 'meador.inge', 'zach.ware', 'eryksun', 'sobolevn'] pr_nums = [] priority = 'normal' resolution = None stage = None status = 'open' superseder = None type = 'behavior' url = 'https://bugs.python.org/issue46585' versions = ['Python 3.11'] ```

sobolevn commented 2 years ago

After looking at https://github.com/python/cpython/blame/8fb36494501aad5b0c1d34311c9743c60bb9926c/Lib/ctypes/test/test_python_api.py#L5-L10 in https://bugs.python.org/issue46584

it seems that we should address this comment:

# This section should be moved into ctypes\__init__.py, when it's ready.

from _ctypes import PyObj_FromPtr

by either:

  1. Making PyObj_FromPtr public by re-exporting it from ctypes
  2. Removing this comment

Arguments for (1):

I don't think that I am familiar with ctypes's history well enough to make an educated dicision here.

But, I would love to work on this after this decision is made :)

eryksun commented 2 years ago

Alternatively, one can cast the address to py_object and dereference its value. For example:

    >>> obj = bytearray(b'spam')
    >>> sys.getrefcount(obj)
    2
    >>> obj2 = ctypes.cast(id(obj), ctypes.py_object).value
    >>> obj2 is obj
    True
    >>> sys.getrefcount(obj)
    3
    >>> del obj2
    >>> sys.getrefcount(obj)
    2