【发布时间】:2021-05-12 13:30:49
【问题描述】:
所以,我有这个代码:
def checkScope(f):
def inner(*args):
res=f(*args)
// I WANNA PRINT HERE BIM BUM AND BAM
return res
return inner
class A():
@checkScope
def first(self):
bim = 5
return self.second(bim)
def second(self,m):
if m < 8:
bum = 6
return self.third()
def third(self):
bam=2
return bam
test=A()
test.first()
如何在函数 checkScope 中使用 Inspect 打印变量 bim bum 和 bam?
【问题讨论】:
-
当你说“我想在这里打印 BIM BUM AND BAM”时,这些变量实际上都不存在 - 作为局部变量,它们在结束时消失了包含函数。
-
正如@jasonharper 提到的,您不能这样做,因为此时变量不再存在。你可以写一个装饰器,如果你在
third函数上使用它,你可以使用inspect.currentframe和inspect.outerframes的组合检查所有外部作用域的局部变量,但我相当有信心没有办法创建一个装饰器,它可以为您提供使用它的函数的局部变量。您必须在函数调用本身中确定这一点。
标签: python python-3.x python-decorators