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

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

Accessing variables in the local scope of a python decorator

问题

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

英文:

Consider:

  1. def g(value):
  2. def f():
  3. return value
  4. return f
  5. x = g(3)
  6. 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中函数的闭包:

  1. >>> def g(value):
  2. ... def f():
  3. ... return value
  4. ... return f
  5. ...
  6. >>> func = g(42)
  7. >>> func.__closure__
  8. (<cell at 0x1077b5a80: int object at 0x1075b4618>,)

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

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

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

  1. &gt;&gt;&gt; def g(value):
  2. ... def f():
  3. ... return value
  4. ... return f
  5. ...
  6. &gt;&gt;&gt; func = g(42)
  7. &gt;&gt;&gt; func.__closure__
  8. (&lt;cell at 0x1077b5a80: int object at 0x1075b4618&gt;,)

Then if you want the value:

  1. &gt;&gt;&gt; cell = func.__closure__[0]
  2. &gt;&gt;&gt; cell.cell_contents
  3. 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:

确定