[C API] Add `PyList_AsTupleAndClear()` function

未關閉
#161,635 4 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

維護者通常 1 天內回覆

還沒有人認領這個 Issue。

  • #161643 來自 @xixi-box —— 已關閉,未合併

評估

難度
4/5
預估耗時
3-5 天
新手友好度
25/100
Issue 類型
功能
描述清晰度
基本清楚
活躍度
停滯
技術堆疊
python
領域
backend

研究方向

Start by reading the existing internal _PyList_AsTupleAndClear() implementation and the public C API declarations and tests; the issue names no file or test path. Check the linked PR for current work. Done means the function is exposed as a public C API and covered by tests for transferring list items into a tuple.

由索引模型根據 Issue 內容生成。

描述

interpreter-core topic-C-API type-feature

Building a tuple when the size if known is advance is easy: allocate a new tuple with PyTuple_New(size) and then fill items using PyTuple_SetItem() or PyTuple_SET_ITEM().

Building a tuple when the final size is not known in advance is more complicated. It's possible to call _PyTuple_Resize() multiple time to resize the tuple. But it's more efficient to build a list, since the list is overallocated and so mutliple "resize" operations are more efficient.

The problem is that PyList_AsTuple() has to call Py_NewRef() on each time to create the tuple, and then call Py_DECREF() on each item when destroying the temporary list. I propose adding a new PyList_AsTupleAndClear() function to transfer items from the list to the tuple and so avoid the useless INCREF/DECREF dance.

PyList_AsTupleAndClear() should only be called when a temporary list is created in the same function and the list cannot be exposed to Python.

In fact, Python already has an internal _PyList_AsTupleAndClear() function, since it's the most efficient way to build a tuple from a list. I just propose to make the function public.

Linked PRs
  • gh-161637
主要語言
Python
星號
78.2k
分支
36.6k
平均合併
19 小時 57 分鐘
30 天內合併 PR
630

環境準備

在 Codespaces 中開啟

在瀏覽器裡用你自己的 GitHub 帳號啟動這個專案的開發容器。

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

python/cpython 的其他 Issue

查看 python/cpython 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。