How to get the list of all initialized objects and function definitions alive in python?
Asked Answered
P

4

61

Say that in the python shell (IDLE) I have defined some classes, functions, variables. Also created objects of the classes. Then I deleted some of the objects and created some others. At a later point in time, how can I get to know what are the currently active objects, variables, and methods definitions active in the memory?

Pulpboard answered 16/12, 2010 at 8:24 Comment(0)
W
74

Yes.

>>> import gc
>>> gc.get_objects()

Not that you'll find that useful. There is a lot of them. :-) Over 4000 just when you start Python.

Possibly a bit more useful is all the variables active locally:

>>> locals()

And the one active globally:

>>> globals()

(Note that "globally" in Python isn't really global as such. For that, you need the gc.get_objects() above, and that you are unlikely to ever find useful, as mentioned).

Wordless answered 16/12, 2010 at 8:29 Comment(2)
Thanks. Exactly what I wanted. But gc.get_objects() gives huge dump. locals() and globals() does fine.Pulpboard
Right. get_objects give what you asked for, locals() and globals() what you wanted. ;-)Wordless
R
16

The function gc.get_objects() will not find all objects, e.g. numpy arrays will not be found.

import numpy as np
import gc

a = np.random.rand(100)
objects = gc.get_objects()
print(any[x is a for x in objects])
# will not find the numpy array

You will need a function that expands all objects, as explained here

# code from https://utcc.utoronto.ca/~cks/space/blog/python/GetAllObjects
import gc
# Recursively expand slist's objects
# into olist, using seen to track
# already processed objects.
def _getr(slist, olist, seen):
  for e in slist:
    if id(e) in seen:
      continue
    seen[id(e)] = None
    olist.append(e)
    tl = gc.get_referents(e)
    if tl:
      _getr(tl, olist, seen)

# The public function.
def get_all_objects():
  """Return a list of all live Python
  objects, not including the list itself."""
  gcl = gc.get_objects()
  olist = []
  seen = {}
  # Just in case:
  seen[id(gcl)] = None
  seen[id(olist)] = None
  seen[id(seen)] = None
  # _getr does the real work.
  _getr(gcl, olist, seen)
  return olist

Now we should be able to find most objects

import numpy as np
import gc

a = np.random.rand(100)
objects = get_all_objects()
print(any[x is a for x in objects])
# will return True, the np.ndarray is found!
Roussillon answered 6/3, 2019 at 15:10 Comment(0)
S
14

How about dir() which will output instantiated objects as a list? I just used this just now: [x for x in dir() if x.lower().startswith('y')]

Speckle answered 17/7, 2020 at 21:16 Comment(0)
I
6

Try globals()

Insecurity answered 16/12, 2010 at 8:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.