How to get an object's name as a string?

Joe Strout joe at strout.net
Tue Oct 28 11:15:50 EDT 2008


On Oct 28, 2008, at 8:41 AM, Shannon Mayne wrote:

> I would like to create objects with algorithmically determined names
> based on other object names and use object names for general algorithm
> input.

What do you mean by the "name" of an object?  Objects don't generally  
have names, unless you explicitly define a .name property and assign  
them names.

(Variables have names, of course, but a variable isn't an object --  
it's just a reference to an object.  Many variables may refer to the  
same object, so it doesn't make any sense to ask for the name of THE  
variable which may be referring to an object at the moment.)

> How would one extract the name of an object from an object instance as
> a string.  I would think that it is stored as an attribute of the
> object but successive 'dir()' calles haven't found me the attribute
> with the namestring.

As noted above, there is no built-in name attribute.  Define one,  
perhaps like this:

class Foo():
  def __init__(name):
    self.name = name

Now your Foo objects have a name attribute, and if "x" is a reference  
to such an object, you would access that as "x.name".

It's still unclear what you intend to do with these, but if at some  
point you want to access objects by their names (from user input or  
whatever), then you'll also need a dictionary to map names to  
objects.  So to your __init__ function, you might add something like  
this:

    name_map[name] = self

where name_map was initialized to {} at the top of the file.  Then you  
can use name_map to look up any object of this class by name.   
Remember that this will keep these objects from automatically  
disappearing when there are no other references (other than the map)  
to them.  If that's a problem, explicitly remove them from the map  
when you know you're done with them, or use weak references.

Best,
- Joe




More information about the Python-list mailing list