Who knows somefunction?
Chad Netzer
cnetzer at mail.arc.nasa.gov
Thu Sep 26 19:13:08 EDT 2002
On Thursday 26 September 2002 14:38, Brian Quinlan wrote:
> Nope. You might want to consider creating your own dictionary to map
> ids to the objects that you are interested in.
That got me thinking about whether there is an easy (and robust) way to
built a dictionary of all the object-id:object pairs in the current
environment.
The following is some dumb code to start with. Does anyone know of a
(non-ridiculous) way to improve it, out of curiosity?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def add_ids_to_dict( l, d ):
all_previously_added = 1
# Add all objects to dict, unless already there
for o in l:
if not d.has_key( id( o ) ):
d[ id( o ) ] = o
# Adding a new object means they weren't already there
all_previously_added = 0
# Give up if all objects in list were already in dict, otherwise
# recurse on all objects in the list
if not all_previously_added:
for o in l:
if hasattr( o, '__dict__' ):
add_ids_to_dict( o.__dict__.keys(), d )
add_ids_to_dict( o.__dict__.values(), d )
else:
add_ids_to_dict( dir( o ), d )
return
if __name__ == '__main__':
objects_dict = {}
add_ids_to_dict( globals(), objects_dict )
print objects_dict
print len( objects_dict.keys() )
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Chad Netzer
cnetzer at mail.arc.nasa.gov
More information about the Python-list
mailing list