【问题标题】:python get current variables of the caller functionpython获取调用者函数的当前变量
【发布时间】:2013-10-31 13:29:17
【问题描述】:
def foo():
    a = 1
    b = 2
    dir() # prints [a, b]
    bar(?) 

der bar(foo_pointer):
    print dir(foo_pointer) # should print [a,b]

我试图使用 bar(sys.modules[__name__].main),但给出的不是[a,b],而是['__call__','__class__' ...],没有ab

我实际上想保护该指针以供以后使用,所以我不能只传递[a,b]

【问题讨论】:

  • Python 没有指针。你到底想在这里实现什么?您始终可以将ab 传递给bar,并将对相同值的引用存储在其他地方。

标签: python dir


【解决方案1】:

使用sys._getframe() function 访问调用框架。框架对象有一个f_locals 属性,让您可以访问该框架的局部变量:

import sys

def bar():
    caller = sys._getframe(1)
    print caller.f_locals

【讨论】:

  • 请注意此函数所承担的警告:CPython implementation detail: This function should be used for internal and specialized purposes only. It is not guaranteed to exist in all implementations of Python.
  • @InbarRose:这就是为什么我直接链接到它而不是 inspect.getcurrentframe() 同义词..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-13
  • 1970-01-01
  • 2016-01-14
  • 2012-08-01
  • 2015-03-26
  • 1970-01-01
  • 2021-08-23
相关资源
最近更新 更多