英文:
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:
>>> def g(value):
... def f():
... return value
... return f
...
>>> func = g(42)
>>> func.__closure__
(<cell at 0x1077b5a80: int object at 0x1075b4618>,)
Then if you want the value:
>>> cell = func.__closure__[0]
>>> cell.cell_contents
42
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论