Getting the name of a variable as a string

前端 未结 23 2710
旧时难觅i
旧时难觅i 2020-11-22 00:19

This thread discusses how to get the name of a function as a string in Python: How to get a function name as a string?

How can I do the same for a variable? As oppose

23条回答
  •  忘掉有多难
    2020-11-22 00:36

    Here's one approach. I wouldn't recommend this for anything important, because it'll be quite brittle. But it can be done.

    Create a function that uses the inspect module to find the source code that called it. Then you can parse the source code to identify the variable names that you want to retrieve. For example, here's a function called autodict that takes a list of variables and returns a dictionary mapping variable names to their values. E.g.:

    x = 'foo'
    y = 'bar'
    d = autodict(x, y)
    print d
    

    Would give:

    {'x': 'foo', 'y': 'bar'}
    

    Inspecting the source code itself is better than searching through the locals() or globals() because the latter approach doesn't tell you which of the variables are the ones you want.

    At any rate, here's the code:

    def autodict(*args):
        get_rid_of = ['autodict(', ',', ')', '\n']
        calling_code = inspect.getouterframes(inspect.currentframe())[1][4][0]
        calling_code = calling_code[calling_code.index('autodict'):]
        for garbage in get_rid_of:
            calling_code = calling_code.replace(garbage, '')
        var_names, var_values = calling_code.split(), args
        dyn_dict = {var_name: var_value for var_name, var_value in
                    zip(var_names, var_values)}
        return dyn_dict
    

    The action happens in the line with inspect.getouterframes, which returns the string within the code that called autodict.

    The obvious downside to this sort of magic is that it makes assumptions about how the source code is structured. And of course, it won't work at all if it's run inside the interpreter.

提交回复
热议问题