我怎样才能对 python 中的嵌套函数执行 %lprun?

How can I do %lprun work on nested function in python?

在 jupyter Notebook 中,我尝试在嵌套函数上使用 %lprun 但我没有成功。

以下代码,在笔记本单元格中

def outerfoo():
    def innerfoo():
        print("Hello World")
        print("Good Bye")
    innerfoo()

%lprun -f outerfoo().innerfoo outerfoo()

输出消息(Hello World 和 GoodBye),但出现此错误后:
使用错误:找不到函数 'outerfoo().innerfoo'。
AttributeError: 'NoneType' 对象没有属性 'innerfoo'

还有这个,

def outerfoo():
    def innerfoo():
        print("Hello World")
        print("Good Bye")
    %lprun -f innerfoo innerfoo()


outerfoo()

不打印消息并给出此错误:
使用错误:找不到函数 'innerfoo'。 NameError: 名称 'innerfoo' 未定义

如何分析 innerfoo

我认为您无法在实际 Python 代码中使用笔记本魔法,因此在功能块中使用 %lprun 可能永远不会奏效。相反,您可以存储对本地函数的全局引用,然后 lprun that:

ref = None
def outerfoo():
    global ref
    def innerfoo():
        print("Hello World")
        print("Good Bye")
    innerfoo()
    ref = innerfoo

# Must be called for `ref` to exist.
outerfoo()

%lprun -f ref ref()

但这一切都让人觉得恶心。您可能一开始就不应该创建嵌套函数。