Simpler way to create dictionary of separate variables?

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

    While this is probably an awful idea, it is along the same lines as rlotun's answer but it'll return the correct result more often.

    import inspect
    def getVarName(getvar):
      frame = inspect.currentframe()
      callerLocals = frame.f_back.f_locals
      for k, v in list(callerLocals.items()):
        if v is getvar():
          callerLocals.pop(k)
          try:
            getvar()
            callerLocals[k] = v
          except NameError:
            callerLocals[k] = v
            del frame
            return k
      del frame
    

    You call it like this:

    bar = True
    foo = False
    bean = False
    fooName = getVarName(lambda: foo)
    print(fooName) # prints "foo"
    

提交回复
热议问题