如何获取函数范围内定义的所有变量的字典?

问题描述 投票:0回答:1

所以我想从函数中获取每个变量作为字典。像这样:

from typing import Any

def myfunc():
  var1 = 10
  var2 = 20
  var3 = 30
  var4 = '40'
  var5 = False

x: dict[str, Any] = myfunc.vars
hardtyped_x = { # What i want x to be. Not including parameters
  'var1': 10,
  'var2': 20,
  'var3': 30,
  'var4': '40',
  'var5': False
}

我尝试询问 tabnine 并得到了类似的信息:

import inspect

def myfunc():
  var1 = 10
  var2 = 20
  var3 = 30
  var4 = '40'
  var5 = False

x = inspect.currentframe().f_back.f_locals

但这要么会引发错误(因为 currentframe() 可以返回 None ,这会引发错误),要么我会得到一长串 dunder 方法和其他类似的东西

python dictionary inspect
1个回答
0
投票

我想出了一个伪方法:

from typing import FunctionType
import inspect

def getFunctionDefinedVariables(function: FunctionType) -> dict:
    with open("TEMPORARYFILE.py", "w") as f:
        codeblock = inspect.getsource(function)
        codeblock = remove_indents_and_top_line
        f.write(codeblock)
        imported_temp_file = __import__("TEMPORARYFILE.py")
        return {key: val for key, val in imported_temp_file.__dict__.items() if not (key.startswith('__') and key.endswith('__'))}

一旦我完成完整功能就会更新

© www.soinside.com 2019 - 2024. All rights reserved.