5.30 如何将变量名和变量值转为字典?

image0

千言万语,不如上示例演示下效果

>>> name="wangbm"
>>> age=28
>>> gender="male"
>>>
>>> convert_vars_to_dict(name, age, gender)
{'name': 'wangbm', 'age': 28, 'gender': 'male'}

convert_vars_to_dict 是我要自己定义的这么一个函数,功能如上,代码如下。

import re
import inspect

def varname(*args):
    current_frame = inspect.currentframe()
    back_frame = current_frame.f_back
    back_frame_info = inspect.getframeinfo(back_frame)

    current_func_name = current_frame.f_code.co_name

    caller_file_path = back_frame_info[0]
    caller_line_no = back_frame_info[1]
    caller_type = back_frame_info[2]
    caller_expression = back_frame_info[3]

    keys = []

    for line in caller_expression:
        re_match = re.search(r'\b{}\((.*?)\)'.format(current_func_name), line)
        match_string = re_match.groups(1)[0]
        keys = [match.strip() for match in match_string.split(',') if match]

    return dict(zip(keys, args))

附上 :inspect 学习文档

image1