Getting the name of a variable as a string

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

    If the goal is to help you keep track of your variables, you can write a simple function that labels the variable and returns its value and type. For example, suppose i_f=3.01 and you round it to an integer called i_n to use in a code, and then need a string i_s that will go into a report.

    def whatis(string, x):
        print(string+' value=',repr(x),type(x))
        return string+' value='+repr(x)+repr(type(x))
    i_f=3.01
    i_n=int(i_f)
    i_s=str(i_n)
    i_l=[i_f, i_n, i_s]
    i_u=(i_f, i_n, i_s)
    
    ## make report that identifies all types
    report='\n'+20*'#'+'\nThis is the report:\n'
    report+= whatis('i_f ',i_f)+'\n'
    report+=whatis('i_n ',i_n)+'\n'
    report+=whatis('i_s ',i_s)+'\n'
    report+=whatis('i_l ',i_l)+'\n'
    report+=whatis('i_u ',i_u)+'\n'
    print(report)
    

    This prints to the window at each call for debugging purposes and also yields a string for the written report. The only downside is that you have to type the variable twice each time you call the function.

    I am a Python newbie and found this very useful way to log my efforts as I program and try to cope with all the objects in Python. One flaw is that whatis() fails if it calls a function described outside the procedure where it is used. For example, int(i_f) was a valid function call only because the int function is known to Python. You could call whatis() using int(i_f**2), but if for some strange reason you choose to define a function called int_squared it must be declared inside the procedure where whatis() is used.

提交回复
热议问题