How can my code discover the name of an object?
Generally speaking, it can’t, because objects don’t really have names. Essentially, assignment always binds a name to a value; the actual name is only known by the namespace it’s in, and a single value can be referenced from many different namespaces (as well as containers).
class A: pass B = A a = B() b = a print b <__main__.A instance at 016D07CC> print a <__main__.A instance at 016D07CC>
Arguably the class has a name: even though it is bound to two names and invoked through the name B the created instance is still reported as an instance of class A. However, it is impossible to say whether the instance’s name is “a” or “b”, since both names are bound to the same value.
Generally speaking it should not be necessary for your code to
know the names of particular values. Unless you are deliberately writing introspective tools, this is usually an indication that a change of approach might be beneficial.
In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to this question:
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!