Finding the instance reference of an object

Larry Bates larry.bates at vitalEsafe.com
Thu Oct 16 12:59:45 EDT 2008


Astley Le Jasper wrote:
> Sorry for the numpty question ...
> 
> How do you find the reference name of an object?
> 
> So if i have this
> 
> bob = modulename.objectname()
> 
> how do i find that the name is 'bob'

Short answer is that you can't.  This because Python's names (bob) are bound to 
objects (modulename.objectname()).  They are NOT variables as they are in 
"other" programming languages.  It is perfectly legal in Python to bind multiple 
names to a single object:

a=b=c=modulename.objectname()

a, b, and c all point to the same object.  An object can have an unlimited 
number of names bound to it.  This is one of the most difficult concepts for 
many beginning Python programmers to understand (I know I had a difficult time 
at first).  It is just not how we taught ourselves to think about "variables" 
and you can write quite a lot of Python treating the names you bind to objects 
like they were "variables".

To accomplish what you want, put your instances in a dictionary.

instances = {}
instances['bob'] = modulename.objectname()
instances['joe'] = modulename.objectname()
.
.
.

Then you can reference them as:

instances[name]

and/or you can pass the name in as an argument to the __init__ method of 
objectname so that it can "hold" the name of the dictionary key that references 
it (good for debugging/logging).

-Larry



More information about the Python-list mailing list