呼び出し元の名前の取得
常山日記経由でメモ。これはすばらしい。
- Chris's Wiki: Finding the name of your caller in Python (http://utcc.utoronto.ca/~cks/space/blog/python/FindingCallersName)
import inspect def getcallerinfo(): fr = inspect.currentframe() try: fr = fr.f_back if fr is None: return '<no caller>' fi = inspect.getframeinfo(fr, 0) if fi[2] == '<module>': return '(%s:%d)' % (fi[0], fi[1]) else: return '%s() (%s:%d)' % (fi[2], fi[0], fi[1]) finally: del fr def foo(): print getcallerinfo() foo() print getcallerinfo() # 実行結果 foo() (test.py:18) (test.py:21)
inspectモジュールは良いドキュメントがないのでいまいち活用できていない。inspect.pyのソースを読んでみるかな。