【问题标题】:How can I get the frame data for a call to list.sort()?如何获取调用 list.sort() 的帧数据?
【发布时间】:2018-09-13 04:50:45
【问题描述】:

我正在尝试访问特定调用 list.sort 方法的帧信息,但我遇到了问题。

import inspect

def calm_pear(x): # compare    
    cur_frame = inspect.currentframe()
    out_frames = inspect.getouterframes(cur_frame)
    print(out_frames[0].function) # prints 'calm_pear'
    print(out_frames[1].function) # prints 'inner'  
    print(out_frames[2].function) # prints 'outer'
    return id(x)

def outer():
    inner()

def inner():
    [0, 1].sort(key=calm_pear)

outer() # call outer

我得到的打印输出是:

    calm_pear
    inner

但是,调用顺序是(outerinnerlist.sortcalm_pear

为什么out_frames[1].function 不像list.sort

【问题讨论】:

    标签: python python-3.x introspection inspect stack-frame


    【解决方案1】:

    list.sort 是用 C 编写的。用 C 编写的函数不会获得 Python 堆栈帧。仅在执行用 Python 编写的代码时才需要 Python 堆栈帧。

    无论您希望通过访问list.sort 的不存在的堆栈框架来做什么,您都必须找到其他方法来实现它。

    【讨论】:

      猜你喜欢
      • 2012-08-17
      • 2013-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多