Convert Variable Name to String?

前端 未结 16 1585
生来不讨喜
生来不讨喜 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

    This is not possible.

    In Python, there really isn't any such thing as a "variable". What Python really has are "names" which can have objects bound to them. It makes no difference to the object what names, if any, it might be bound to. It might be bound to dozens of different names, or none.

    Consider this example:

    foo = 1
    bar = 1
    baz = 1
    

    Now, suppose you have the integer object with value 1, and you want to work backwards and find its name. What would you print? Three different names have that object bound to them, and all are equally valid.

    In Python, a name is a way to access an object, so there is no way to work with names directly. There might be some clever way to hack the Python bytecodes or something to get the value of the name, but that is at best a parlor trick.

    If you know you want print foo to print "foo", you might as well just execute print "foo" in the first place.

    EDIT: I have changed the wording slightly to make this more clear. Also, here is an even better example:

    foo = 1
    bar = foo
    baz = foo
    

    In practice, Python reuses the same object for integers with common values like 0 or 1, so the first example should bind the same object to all three names. But this example is crystal clear: the same object is bound to foo, bar, and baz.

提交回复
热议问题