如何在python中获取所有已初始化对象和函数定义的列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4458701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:49:42  来源:igfitidea点击:

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

pythonmemorypython-idle

提问by

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?

假设在 python shell (IDLE) 中我定义了一些类、函数、变量。还创建了类的对象。然后我删除了一些对象并创建了一些其他对象。在稍后的某个时间点,我如何才能知道内存中当前活动的对象、变量和方法定义是什么?

采纳答案by Lennart Regebro

Yes.

是的。

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

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

并不是说你会发现它很有用。有很多。:-) 仅当您启动 Python 时就超过 4000。

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 globalas such. For that, you need the gc.get_objects()above, and that you are unlikely to ever find useful, as mentioned).

(请注意,Python 中的“全局”并不是真正的全局。为此,您需要gc.get_objects()上述内容,并且如上所述,您不太可能觉得有用)。

回答by NPE

回答by skjerns

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

该函数gc.get_objects()不会找到所有对象,例如不会找到 numpy 数组。

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 mostobjects

现在我们应该能够找到大多数对象

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!