Python 为什么inspect.stack()不能正常工作?

Python 为什么inspect.stack()不能正常工作?,python,stack,Python,Stack,我正在尝试写入当前执行函数的名称。但它不能正常工作。 当我将'print inspect.stack()[0][3]放在def func()之后时,它会工作,但当我尝试将此命令放在if之后时,它不会打印任何内容 import inspect debug = True def debug(): print inspect.stack()[0][3] if debug==True: print "test" print inspect.stack(

我正在尝试写入当前执行函数的名称。但它不能正常工作。 当我将
'print inspect.stack()[0][3]
放在
def func()
之后时,它会工作,但当我尝试将此命令放在if之后时,它不会打印任何内容

import inspect

debug = True

def debug():
    print inspect.stack()[0][3]
    if debug==True:
        print "test"
        print inspect.stack()[0][3]

debug()
返回
'debug'
,但它应该返回

'debug'\n'test'\n'debug'

问题出在哪里?

在Python3和High中,如果需要,您需要使用print()。如果在定义函数时没有(),它将成为语法错误,并且不会打印任何内容:

def debug():
您正在从全局范围中丢失对先前创建的变量
debug
的最后一次引用。您可以将
debug
变量从布尔值
True
重新定义为函数引用。因此不满足条件
debug==True
(因为
debug
现在是一个函数,而不是布尔值)。因此,只有第一个
print
语句有效(请参阅)

这将按预期工作,例如:

import inspect

debug = True

def f():
    print inspect.stack()[0][3]
    if debug==True:
        print "test"
        print inspect.stack()[0][3]

f()

这是Python中的一个常见错误,尤其是习惯于使用其他语言的人,在这些语言中,函数名是以一种特殊的方式处理的。在Python中,它们不是-定义函数后,可以将其名称用作任何其他变量。这有很多优点,但正如这里看到的,有时可能会令人困惑。

OP说代码运行时没有错误,所以显然这不是关于Python 3的。