Hi Everyone,

Thanks in advance for any help. I am fairly new to programming python, and I and another person are developing a simple educational (graphical) tool that shows variable referencing for any python code that I run in my own defined local and global name spaces.

The problem I am having is the following:

I want to graphically display the name of the variable that is storing the information. i.e. I have a variable 'word' and it references the string "example". The variable is passed to a function that overloads the __add__ operator. We want to display on the screen the variable name that is being used to add with but being as it is being passed to a function
I have no idea at any given point which two variables are being added.

How I would solve this in C would be to grab the memory address of each variable and make a hash table relating the address to the name, and when I came across the memory
address I know i'm talking about a specific variable, hence i know what variable name to display on the screen.

Is there anyway to do this in Python?

Thank you!

You could use id():

word = "example"

print id(word)  # eg. 41369728

Let me warn you, Python really used the globals dictionary to match variable name with content.

Well, at first I thought what you want to do would require the traceback module.

Now that I think about it, I think you use id.

def get_var_name(arg):
  for x in globals():
    if id(globals()[x]) == id(arg):
      return x
  return

Edited 6 Years Ago by jcao219: n/a

This article has been dead for over six months. Start a new discussion instead.