[PYTHON] Get the variable name of the variable as a character string.

I wanted it for debugging, so I made it myself. In python, there is a built-in variable in the namespace, so search for it. (Use namespace variables locals () and globals ().) The reference of the variable is not unique, but the reference destination of the variable is unique (... isn't it?). (Use the identifier function ʻid () `.)

def getVarsNames( _vars, symboltable ) :
    """
    This is wrapper of getVarName() for a list references.
    """
    return [ getVarName( var, symboltable ) for var in _vars ]

def getVarName( var, symboltable, error=None ) :
    """
    Return a var's name as a string.\nThis funciton require a symboltable(returned value of globals() or locals()) in the name space where you search the var's name.\nIf you set error='exception', this raise a ValueError when the searching failed.
    """
    for k,v in symboltable.iteritems() :
        if id(v) == id(var) :
            return k
    else :
        if error == "exception" :
            raise ValueError("Undefined function is mixed in subspace?")
        else:
            return error

if __name__ == "__main__":
    a = 4
    b = "ahoo"
    print getVarsNames([a,b,"c"],locals())

This is the return value.

['a', 'b', None]

what about? What happens if you call it from a function that is nested repeatedly?

Postscript: Feel free to send exceptions.

Recommended Posts

Get the variable name of the variable as a character string.
[PowerShell] Get the reading of the character string
# Function that returns the character code of a string
[Python] I tried to get the type name as a string from the type function
Extract the value of dict or list as a string
<Python> A quiz to batch convert file names separated by a specific character string as part of the file name
pandas Fetch the name of a column that contains a specific character
[Python] Get the variable name with str
[Python] Get the character code of the file
Get the filename of a directory (glob)
Get the formula in an excel file as a string in Python
Get the caller of a function in Python
[NNabla] How to get the output (variable) of the middle layer of a pre-built network
How to get the variable name itself in python
Get the file name in a folder using glob
Cut a part of the string using a Python slice
[C language] [Linux] Get the value of environment variable
A story about changing the master name of BlueZ
Output the output result of sklearn.metrics.classification_report as a CSV file
Calculate the product of matrices with a character expression?
Python Note: The mystery of assigning a variable to a variable
[Ansible] Example of playbook that adds a character string to the first line of the file
When a local variable with the same name as a global variable is defined in the function
Get the number of digits
Get the output value of the command (as received by xargs)
Find out the apparent width of a string in python
Get the id of a GPU with low memory usage
Get UNIXTIME at the beginning of today with a command
Get the number of specific elements in a python list
To get the name of the primitive etc. generated immediately before
Get the host name of the host PC with Docker on Linux
How to connect the contents of a list into a string
[Linux] [C / C ++] How to get the return address value of a function and the function name of the caller
[Python] Programming to find the number of a in a character string that repeats a specified number of times.
How to quickly count the frequency of appearance of characters from a character string in Python?
When a character string of a certain series is in the Key of the dictionary, the character string is converted to the Value of the dictionary.
I want to get the name of the function / method being executed
Save the result of the life game as a gif with python
Get the number of views of Qiita
Is it a character string operation?
[Introduction to Python] How to split a character string with the split function
Format when passing a long string as an argument of python
How to check the memory size of a variable in Python
Get the attributes of an object
Outputs a line containing the specified character string from a text file
[Python] Get the update date of a news article from HTML
Get the first element of queryset
Get the URL of a JIRA ticket created with the jira-python library
How to get the vertex coordinates of a feature in ArcPy
How to extract the desired character string from a line 4 commands
Get the number of Youtube subscribers
Try using Elasticsearch as the foundation of a question answering system
Get the host name in Python
Create a function to get the contents of the database in Go
[Golang] Check if a specific character string is included in the character string
The story of writing a program
Get the query string (query string) in Django
Get the number of readers of a treatise on Mendeley in Python
Python> Slice> A slice offset earlier than the beginning of a string is treated as 0, and one after the end is treated as -1
Web scraping beginners tried to make a command to get the movie name of next Friday Road Show
The story of making a tool to load an image with Python ⇒ save it as another name