python / python/cpython

Misleading errors and confusing behavior with zero-argument `super()` in inner functions

未關閉
#98,349 2 則留言 1 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

interpreter-core type-bug
主要語言
Python
星號
77.2k
分支
36k
PR 合併指標
PR 指標待擷取

描述

Bug report

See also: #90333.

super() exhibits behavior subtly broken in different ways when used in inner functions with zero arguments:

class Foo:
    def __init__(self):
        def inner():
            print(str(super()))

        inner()

>>> Foo()
...
RuntimeError: super(): no arguments

and in inner functions that do take arguments:

class Foo:
    def __init__(self):
        def inner(_=1):
            print(str(super()))

        inner()

>>> Foo()
...
TypeError: super(type, obj): obj must be an instance or subtype of type

...unless the first argument is None:

class Foo:
    def __init__(self):
        def inner(_=None):
            print(str(super()))

        inner()

>>> Foo()
<super: <class 'Foo'>, NULL>

but then method lookup doesn't work as expected (raises AttributeError trying to access any method not defined on NoneType).

__class__ gets injected into the code properly, it just seems that super() assumes the first argument of the immediately enclosing function is self.

It seems to me that:

  • The best case would be for this behavior to look up self from the same scope __class__ was defined in rather than the immediate scope where super() was invoked, making it possible to use zero-argument super in nested functions
  • If that is not possible, a consistent error should be raised regardless of the arguments to the immediately-enclosing function; all three of those examples should communicate that zero-argument super in nested functions is not supported. Especially the first error message is misleading, since it describes two-argument super.
  • If zero-argument super() is not made to work in nested functions, this quirk should be clearly documented. Right now the documentation only vaguely hints at problems:

    Also note that, aside from the zero argument form, super() is not limited to use inside methods.

I'd be happy to work on this but am concerned there might be a lot of edge-cases that are not obvious to me (like the workaround for super() being called from the C-API before a MAKE_CELL).

Your environment

  • CPython versions tested on: 3.10.7, 3.12 dev @ eae7dad40255bad42e4abce53ff8143dcbc66af5
  • Operating system and architecture: Linux x86_64

貢獻指南

開啟貢獻指南

從這裡開始

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

研究方向

首先重現 issue 中的三個巢狀函式範例,並比較它們的無參數 super() 行為。閱讀無參數 super() 的文件,並調查提到的 class、MAKE_CELL 和 C-API 互動。完成的標準是確定一致的行為、統一的錯誤或受支援的查找語意,以及相應的回歸涵蓋或文件。

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

評估

技術堆疊
python
領域
compilers
Issue 類型
缺陷
難度
5/5
預估耗時
一週以上
活躍度
停滯
描述清晰度
基本清楚
新手友好度
25/100

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

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