0

メモリ リークを調査していて、オブジェクトをトラバースする方法を探していました。次のコードを思いつきました。

def obj_scan(obj, path, fname):
    def _store(msg):
        open(fname, 'a').write(path+msg+'\n')

    try:
        if callable(obj):
            return
        obj_type = type(obj)
        if obj_type is str:
            _store('- STR {}'.format(len(obj)))
        elif obj is None:
            _store('- NONE')
        elif obj_type is int:
            _store('- INT')
        elif obj_type is list:
            for idx, val in enumerate(obj):
                obj_scan(val, '{}[{}]'.format(path, idx), fname)
        elif obj_type is dict:
            for key, val in obj.iteritems():
                fmt_line = '{}['+('"{}"]' if type(key) is str else ']')
                obj_scan(val, fmt_line.format(path, key), fname)
        else:
            for attr in dir(obj):
                if ('.'+attr) in path and attr != '__dict__':
                    count = path.count('.'+attr)+1
                    _store('.{} - ATTR repeated {}{}'.format(attr, count, ' - BACTRACKING'*(count>10)))
                    if count>10:
                        return
                obj_scan(getattr(obj, attr), '{}.{}'.format(path, attr), fname)
    except Exception as msg:
        _store('Recursion limit exceeded')

私の質問は - これを行うためのより効率的な方法はありますか? (私は知っています - 出力は美人コンテストに勝つことはありません)

4

0 に答える 0