How to write a function to return the variable name?

后端 未结 6 1376
自闭症患者
自闭症患者 2020-12-04 03:59

I want a function that can return the variable/object name as str like this :

def get_variable_name (input_variable):
    ## some codes

>>get_variable         


        
6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 04:53

    I've seen a few variants on this kind of question several times on SO now. The answer is don't. Learn to use a dict anytime you need association between names and objects. You will thank yourself for this later.

    In answer to the question "How can my code discover the name of an object?", here's a quote from Fredrik Lundh (on comp.lang.python):

    The same way as you get the name of that cat you found on your porch: the cat (object) itself cannot tell you its name, and it doesn’t really care — so the only way to find out what it’s called is to ask all your neighbours (namespaces) if it’s their cat (object)…

    ….and don’t be surprised if you’ll find that it’s known by many names, or no name at all!


    Note: It is technically possible to get a list of the names which are bound to an object, at least in CPython implementation. If you're interested to see that demonstrated, see the usage of the inspect module shown in my answer here:

    Can an object inspect the name of the variable it's been assigned to?

    This technique should only be used in some crazy debugging session, don't use anything like this in your design.

提交回复
热议问题