0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

python の gc でクラス毎のオブジェクト数を確認

Posted at

やりたいこと

クラス毎にオブジェクト数を確認する。

gc

gc.get_objects() で全オブジェクトを取得することができ、isinstance(obj, Class) でクラス毎のオブジェクトを判定することができる。

プログラム例

test1.py
import gc


class ParentA:
    pass

class A(ParentA):
    pass

class ParentB:
    pass

class B(ParentB):
    pass


def main():
    pa = [ParentA(), ParentA()]
    a = [A(), A()]

    pb = [ParentB(), ParentB(), ParentB()]
    b = [B(), B(), B()]

    num_pa = 0
    num_a = 0
    num_pb = 0
    num_b = 0

    objs = gc.get_objects()
    for obj in objs:
        if isinstance(obj, ParentA):
            print(f"is ParentA: {obj}")
            num_pa += 1
        if isinstance(obj, A):
            print(f"is A: {obj}")
            num_a += 1
        if isinstance(obj, ParentB):
            print(f"is ParentB: {obj}")
            num_pb += 1
        if isinstance(obj, B):
            print(f"is B: {obj}")
            num_b += 1

    print(f"ParentA: {num_pa}")
    print(f"A:       {num_a}")
    print(f"ParentB: {num_pb}")
    print(f"B:       {num_b}")

    return 0


if __name__ == '__main__':
    res = main()
    exit(res)

実行結果

$ python test1.py
is ParentA: <__main__.ParentA object at 0x7f8d4bea3470>
is ParentA: <__main__.ParentA object at 0x7f8d4bea33e0>
is ParentA: <__main__.A object at 0x7f8d4bea3410>
is A: <__main__.A object at 0x7f8d4bea3410>
is ParentA: <__main__.A object at 0x7f8d4bea3620>
is A: <__main__.A object at 0x7f8d4bea3620>
is ParentB: <__main__.ParentB object at 0x7f8d4bea3650>
is ParentB: <__main__.ParentB object at 0x7f8d4bea3680>
is ParentB: <__main__.ParentB object at 0x7f8d4bea36b0>
is ParentB: <__main__.B object at 0x7f8d4bea36e0>
is B: <__main__.B object at 0x7f8d4bea36e0>
is ParentB: <__main__.B object at 0x7f8d4bea3710>
is B: <__main__.B object at 0x7f8d4bea3710>
is ParentB: <__main__.B object at 0x7f8d4bea3740>
is B: <__main__.B object at 0x7f8d4bea3740>

ParentA: 4
A:       2
ParentB: 6
B:       3

各クラスのオブジェクト数が出力される。
isinstance(obj, Class) は親クラスも True となるため、ParentA、ParentB はそれぞれ A、B のオブジェクトを含む。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?