Simpler way to create dictionary of separate variables?

前端 未结 27 2370
名媛妹妹
名媛妹妹 2020-11-22 02:42

I would like to be able to get the name of a variable as a string but I don\'t know if Python has that much introspection capabilities. Something like:

>&         


        
27条回答
  •  天涯浪人
    2020-11-22 03:28

    I wrote a neat little useful function based on the answer to this question. I'm putting it here in case it's useful.

    def what(obj, callingLocals=locals()):
        """
        quick function to print name of input and value. 
        If not for the default-Valued callingLocals, the function would always
        get the name as "obj", which is not what I want.    
        """
        for k, v in list(callingLocals.items()):
             if v is obj:
                name = k
        print(name, "=", obj)
    

    usage:

    >> a = 4
    >> what(a)
    a = 4
    >>|
    

提交回复
热议问题