27
28

More than 5 years have passed since last update.

python でよくわからないオブジェクトの中身を表示する

Posted at

Tensorflow 等を使っていると、このオブジェクトは一体なんのクラスのインスタンスで、どんな情報(プロパティ)を持っているのだろう、とわからなくなるときがしばしばあります。
しかも、まともなドキュメントが無いこともしばしばあります。
(例えば BeamSearchDecoderOutput など)

このような時に便利な関数 explain を作りました。

tf.constant の戻り値を調べてみましょう。

In [7]: tensor = tf.constant([[1, 2], [3, 4]])

In [8]: explain(tensor)
EXPLAIN ------------------
Tensor("Const_2:0", shape=(2, 2), dtype=int32)
<class 'tensorflow.python.framework.ops.Tensor'>
ATTRIBUTES:
OVERLOADABLE_OPERATORS: {'__truediv__', '__mul__', '__rpow__', '__rdiv__', '__neg__', '__pow__', '__rmul__', '__or__', '__rxor__', '__div__', '__ge__', '__rfloordiv__', '__lt__', '__gt__', '__getitem__', '__rand__', '__add__', '__abs__', '__invert__', '__rmatmul__', '__rsub__', '__floordiv__', '__xor__', '__ror__', '__rtruediv__', '__and__', '__sub__', '__radd__', '__matmul__', '__le__', '__rmod__', '__mod__'}
device:
dtype:  <dtype: 'int32'>
graph:  <tensorflow.python.framework.ops.Graph object at 0x119f61d30>
name:   Const_2:0
op: name: "Const_2"
op: "Const"
attr {
  key: "dtype"
  value {
    type: DT_INT32
  }
}
attr {
  key: "value"
  value {
    tensor {
      dtype: DT_INT32
      tensor_shape {
        dim {
          size: 2
        }
        dim {
          size: 2
        }
      }
      tensor_content: "\001\000\000\000\002\000\000\000\003\000\000\000\004\000\000\000"
    }
  }
}

shape:  (2, 2)
value_index:    0

型は Tensor で、名前をとるのは name でとれて・・といったことがわかります。
皆様の闇デバッグ作業に役立てれば幸いです。
(存在するプロパティを勝手に叩いてしまうので、プロパティ読み出しの中で危ない処理をやる不法者なオブジェクトにはご注意下さい)

実装

import types


def explain(item, shows_private=False, shows_method=False):
    '''
    与えた python オブジェクトの詳細を表示します。
    '''
    print('EXPLAIN ------------------')
    print(item)
    print(type(item))
    print('ATTRIBUTES:')
    for d in dir(item):
        if d == 'type':
            continue
        if not shows_private and d.startswith('_'):
            continue
        attr = getattr(item, d)
        if not shows_method and (
                isinstance(attr, types.MethodType) or
                isinstance(attr, types.BuiltinMethodType) or
                isinstance(attr, types.CoroutineType) or
                isinstance(attr, types.FunctionType) or
                isinstance(attr, types.BuiltinFunctionType) or
                isinstance(attr, types.GeneratorType)
        ):
            continue
        print('{}:\t{}'.format(d, attr))
27
28
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
27
28