How do I access Python's dictionary of all global variables?

Josiah Carlson jcarlson at nospam.uci.edu
Sat Feb 21 13:27:27 EST 2004


Cameron already dealt with globals, so I'll try to tackle this one.

> Is it possible to iterate through all variables in all scopes in all objects?

Quick answer: no

Long answer: you would need to get access to every object pointer in the 
entirety of the interpreter.  I'm sure this could probably be done with 
a C extension module that returned a list of every object in existance 
by hooking into the garbage collector, but you really don't want to do 
this, because you'd get references to EVERYTHING, including functions, 
methods, C extension functions, etc.

A better idea would be to use weakrefs to keep references to every live 
object that you care about, and if you desire, search through those:

class myobject:
     __olist = {}
     def __init__(self):
         #create a weak reference to yourself
         #place it in the __olist
         self.__olist[id(self)] = ref(self)
     def __del__(self):
         del self.__olist[id(self)]
     def get_olist(self):
         #this creates a hard reference to every object
         return [o() for o in self.__olist.values() if o() is not None]


  - Josiah



More information about the Python-list mailing list