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!

Dani AI

Generated

Short answer: there is no reliable, general way for an object to know “the variable name” that referred to it when it was passed into add (or any function). Names in Python are bindings in a namespace, not properties of the object. and pointed toward matching identities in a namespace; that can help for simple demos but is brittle in real code.

Why it breaks: a single object can have many names; expressions and temporaries have no caller-side name; CPython interns small ints and some strings so identities are shared; objects created at C level or outside the inspected frame may not appear where you expect; and optimized frames/closures can hide bindings. ’s intuition about assignment touching identity is useful — assignment binds names to objects — but it doesn’t give a unique, discoverable “original name.”

Practical approaches that work for an educational visualizer:

  • Make names explicit by wrapping values in a small proxy that carries a label and implements the arithmetic operators. This keeps name information with the value and is deterministic. Example pattern:
class Tracked:
    def __init__(self, name, value):
        self.name = name
        self.value = value

    def __add__(self, other):
        other_name = getattr(other, "name", repr(other))
        result = self.value + (other.value if hasattr(other, "value") else other)
        return Tracked(f"{self.name}+{other_name}", result)

    def __repr__(self):
        return f"<{self.name}: {self.value!r}>"
  • For instrumenting arbitrary user code, transform the code with the ast module (replace Name loads with tracked lookups) or execute user code in a prepared namespace that maps names to Tracked wrappers. Both require careful handling of exec/eval, imports and performance tradeoffs.

Recommendation: for an education tool prefer explicit wrappers or AST instrumentation. Use id()/frame-scanning only as a last-resort debugging aid and document its many edge cases.

Recommended Answers

All 3 Replies

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.

in python assignment always create a new variable. So it doesn't have any pointers

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
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.