Simpler way to create dictionary of separate variables?

前端 未结 27 1895
名媛妹妹
名媛妹妹 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:18

    On python3, this function will get the outer most name in the stack:

    import inspect
    
    
    def retrieve_name(var):
            """
            Gets the name of var. Does it from the out most frame inner-wards.
            :param var: variable to get name from.
            :return: string
            """
            for fi in reversed(inspect.stack()):
                names = [var_name for var_name, var_val in fi.frame.f_locals.items() if var_val is var]
                if len(names) > 0:
                    return names[0]
    

    It is useful anywhere on the code. Traverses the reversed stack looking for the first match.

提交回复
热议问题