Converting a string into an object instance

Michael P. Reilly arcege at
Wed Aug 18 00:22:27 CEST 1999

bowman <bowman at> wrote:
: Given a string representation of an object, like you would get from
: id(), is there anyway to get back the actual object? 

The value that id() returns is defined to be the object's identity, and
is only currently implimented as the object's memory address but does not
need to be.  The value is just said to be unique to that address, which
means its use in Tkinter is good, but using the value of id() does not
give you the object back.

: As background, in Tkinter, it is possible to create a menu, add
: cascades, and then set the 'menu' attribute of a Toplevel object to that
: menu, producing a menubar. If you then create another menu containing
: the pulldown entries, you can attach this menu to the toplevel cascades
: with

:    topMenu.entryconfigure(index, menu=pullDown)

: So far, so good. However, if you then want to walk the menu tree, 
:    topMenu.entrycget(index, 'menu') 

: will return a string such as .135753368.135845912, and not a copy of the
: menu object.  This is indeed the same thing you get if you 'print
: pullDown', but is not too useful for manipulating the attributes or
: entries of the menu.

True, it isn't all that useful; the common method is to save the widget
when you want to use it later.

: It is easy enough to just refer to the menu directly, but in some
: instances it might be useful to have the ability to modify the 4th entry
: in the 3rd cascade with only a reference to the top level object.

Since the object's identity is unique, it's good to use as a hash value
(in fact, it is the default hash value for a class), so you can create
a dictionary that captures the information for you:
  widget_map = {}
  widget_map[str(widget)] = widget

But for this problem specifically, you can use my MenuEntry module:

It lets you do something like the following:
  menu = Menu(mbutton)
  open = MenuCommand(menu, label='Open...', command=self.openfile_dialog)
  save = MenuCommand(menu, label='Save', command=self.savefile_default)
  saveas = MenuCommand(menu, label='Save...', command=self.savefile_dialog)
  MenuCommand(menu, label='Quit', command=self.quitapp)
  save.config(state=DISABLED)  # "grey-out" the menu option
  print save['label']

MenuCascade objects create a submenu for you (called "submenu").


More information about the Python-list mailing list