Convert Variable Name to String?

前端 未结 16 1602
生来不讨喜
生来不讨喜 2020-11-28 04:33

I would like to convert a python variable name into the string equivalent as shown. Any ideas how?

var = {}
print ???  # Would like to see \'var\'
something_         


        
16条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 05:14

    What are you trying to achieve? There is absolutely no reason to ever do what you describe, and there is likely a much better solution to the problem you're trying to solve..

    The most obvious alternative to what you request is a dictionary. For example:

    >>> my_data = {'var': 'something'}
    >>> my_data['something_else'] = 'something'
    >>> print my_data.keys()
    ['var', 'something_else']
    >>> print my_data['var']
    something
    

    Mostly as a.. challenge, I implemented your desired output. Do not use this code, please!

    #!/usr/bin/env python2.6
    class NewLocals:
        """Please don't ever use this code.."""
        def __init__(self, initial_locals):
            self.prev_locals = list(initial_locals.keys())
    
        def show_new(self, new_locals):
            output = ", ".join(list(set(new_locals) - set(self.prev_locals)))
            self.prev_locals = list(new_locals.keys())
            return output
    # Set up
    eww = None
    eww = NewLocals(locals())
    
    # "Working" requested code
    
    var = {}
    
    print eww.show_new(locals())  # Outputs: var
    
    something_else = 3
    print eww.show_new(locals()) # Outputs: something_else
    
    # Further testing
    
    another_variable = 4
    and_a_final_one = 5
    
    print eww.show_new(locals()) # Outputs: another_variable, and_a_final_one
    

提交回复
热议问题