如何获取Python中所有已初始化对象和函数定义的列表?
假设在Python的命令行界面(IDLE)中,我定义了一些类、函数和变量,还创建了一些类的对象。然后我删除了一些对象,又创建了一些新的对象。过了一段时间后,我想知道现在内存中有哪些对象、变量和方法是活跃的,怎么查看呢?
4 个回答
13
你觉得 dir()
这个函数怎么样?它会把当前创建的对象列成一个列表。我刚才就用过这个:
[x for x in dir() if x.lower().startswith('y')]
这段代码的意思是:从 dir()
输出的列表中,找出所有以字母 'y' 开头的对象,并把它们放到一个新的列表里。
15
函数 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
你需要一个可以扩展所有对象的函数,具体的说明可以在 这里 找到。
# 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
现在我们应该能够找到 大部分 对象了。
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!
74
是的。
>>> import gc
>>> gc.get_objects()
不过你可能觉得这没什么用。实际上,这种东西有很多很多。:-) 刚开始学Python的时候,就有超过4000个。
可能更有用的是你当前作用域内的所有变量:
>>> locals()
还有一个是全局的:
>>> globals()
(注意,在Python中,“全局”并不完全等同于全局。如果你想要真正的全局变量,你需要使用上面提到的gc.get_objects()
,不过这通常也没什么用,正如之前提到的)。