Getting the name of a variable as a string

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

    Following method will not return the name of variable but using this method you can create data frame easily if variable is available in global scope.

    class CustomDict(dict):
        def __add__(self, other):
            return CustomDict({**self, **other})
    
    class GlobalBase(type):
        def __getattr__(cls, key):
            return CustomDict({key: globals()[key]})
    
        def __getitem__(cls, keys):
            return CustomDict({key: globals()[key] for key in keys})
    
    class G(metaclass=GlobalBase):
        pass
    
    x, y, z = 0, 1, 2
    
    print('method 1:', G['x', 'y', 'z']) # Outcome: method 1: {'x': 0, 'y': 1, 'z': 2}
    print('method 2:', G.x + G.y + G.z) # Outcome: method 2: {'x': 0, 'y': 1, 'z': 2}
    
    A = [0, 1]
    B = [1, 2]
    pd.DataFrame(G.A + G.B) # It will return a data frame with A and B columns
    

提交回复
热议问题