Simpler way to create dictionary of separate variables?

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

    With python-varname you can easily do it:

    pip install python-varname

    from varname import Wrapper
    
    foo = Wrapper(True)
    bar = Wrapper(False)
    
    your_dict = {val.name: val.value for val in (foo, bar)}
    
    print(your_dict)
    
    # {'foo': True, 'bar': False}
    

    Disclaimer: I'm the author of that python-varname library.

提交回复
热议问题