访问 Python 装饰器的局部作用域中的变量

huangapple go评论64阅读模式
英文:

Accessing variables in the local scope of a python decorator

问题

在示例中给定的 x,即从 g(3) 返回的闭包,是否有办法在不调用 x() 的情况下检查 value 的值?

英文:

Consider:

def g(value):
    def f():
        return value
    return f

x = g(3)
x() # prints 3

Given x in the example, the returned closure from g(3), is there any way to inspect that is the value of value without calling x()?

答案1

得分: 0

是的,你可以直接审查Python中函数的闭包:

>>> def g(value):
...     def f():
...         return value
...     return f
...
>>> func = g(42)
>>> func.__closure__
(<cell at 0x1077b5a80: int object at 0x1075b4618>,)

然后,如果你想要获取值:

>>> cell =  func.__closure__[0]
>>> cell.cell_contents
42
英文:

Yes, you can directly introspect the closure for a function in Python:

&gt;&gt;&gt; def g(value):
...     def f():
...         return value
...     return f
...
&gt;&gt;&gt; func = g(42)
&gt;&gt;&gt; func.__closure__
(&lt;cell at 0x1077b5a80: int object at 0x1075b4618&gt;,)

Then if you want the value:

&gt;&gt;&gt; cell =  func.__closure__[0]
&gt;&gt;&gt; cell.cell_contents
42

huangapple
  • 本文由 发表于 2023年5月28日 11:45:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76349851.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定