python / python/cpython

Inconsistent handling of the modulo argument for ternary pow() (pure-Python vs extension)

未关闭
#151,118 2 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

interpreter-core type-bug
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

Bug report

Bug description:

This is a follow-up of the https://github.com/python/cpython/issues/130104.

An example with the stdlib:

>>> import decimal, _pydecimal
>>> pow(2, 3, decimal.Decimal(4))
Decimal('0')
>>> pow(2, 3, _pydecimal.Decimal(4))
Traceback (most recent call last):
  File "<python-input-5>", line 1, in <module>
    pow(2, 3, _pydecimal.Decimal(4))
    ~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: unsupported operand type(s) for ** or pow(): 'int', 'int', 'Decimal'

IIUIC, pow() it just calls the __pow__() for the third argument with original order of ops as a fallback. So, we can just do something like this:

diff --git a/Objects/typeobject.c b/Objects/typeobject.c
index 14bc5a4bc4..911c890fcb 100644
--- a/Objects/typeobject.c
+++ b/Objects/typeobject.c
@@ -10377,7 +10377,27 @@ slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
         stack[2] = modulus;
         return vectorcall_maybe(tstate, &_Py_ID(__rpow__), stack, 3);
     }
-    Py_RETURN_NOTIMPLEMENTED;
+    stack[0] = self;
+    stack[1] = other;
+    stack[2] = modulus;
+
+    _PyCStackRef cref;
+    _PyThreadState_PushCStackRef(tstate, &cref);
+    int unbound = lookup_maybe_method(modulus, &_Py_ID(__pow__), &cref.ref);
+    PyObject *func = PyStackRef_AsPyObjectBorrow(cref.ref);
+
+    if (func == NULL) {
+        _PyThreadState_PopCStackRef(tstate, &cref);
+        if (!PyErr_Occurred()) {
+            Py_RETURN_NOTIMPLEMENTED;
+        }
+        return NULL;
+    }
+
+    PyObject *retval = vectorcall_unbound(tstate, unbound, func, stack, 3);
+
+    _PyThreadState_PopCStackRef(tstate, &cref);
+    return retval;
 }
 
 SLOT0(slot_nb_negative, __neg__)

Full patch: https://github.com/skirpichev/cpython/pull/9

CPython versions tested on:

CPython main branch

Operating systems tested on:

No response

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 Objects/typeobject.c 中的 slot_nb_power 开始,在 CPython main 构建上重现报告中的 decimal/_pydecimal 示例。比较 Pure-Python 实现与扩展实现之间 ternary pow() 的行为;完成标准是两者都能一致地处理 modulo 参数,且不会使现有的 fallback 行为发生回归。

由索引模型根据 Issue 内容生成。

评估

技术栈
c, python
领域
compilers
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
冷清
描述清晰度
基本清楚
新手友好度
45/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。