Getting the name of a variable as a string

前端 未结 23 2955
旧时难觅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:38

    This function will print variable name with its value:

    import inspect
    
    def print_this(var):
        callers_local_vars = inspect.currentframe().f_back.f_locals.items()
        print(str([k for k, v in callers_local_vars if v is var][0])+': '+str(var))
    
    ***Input & Function call:***
    my_var = 10
    
    print_this(my_var)
    
    ***Output**:*
    my_var: 10
    

提交回复
热议问题