Convert Variable Name to String?

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

    I think this is a cool solution and I suppose the best you can get. But do you see any way to handle the ambigious results, your function may return? As "is" operator behaves unexpectedly with integers shows, low integers and strings of the same value get cached by python so that your variablename-function might priovide ambigous results with a high probability. In my case, I would like to create a decorator, that adds a new variable to a class by the varialbename i pass it:

    def inject(klass, dependency):
    klass.__dict__["__"+variablename(dependency)]=dependency
    

    But if your method returns ambigous results, how can I know the name of the variable I added?

    var any_var="myvarcontent"
    var myvar="myvarcontent"
    @inject(myvar)
    class myclasss():
        def myclass_method(self):
            print self.__myvar    #I can not be sure, that this variable will be set...
    

    Maybe if I will also check the local list I could at least remove the "dependency"-Variable from the list, but this will not be a reliable result.

提交回复
热议问题