<Python> 関数名と行番号を取得する。

デバックdebugしてる時に、関数名function nameと行番号line numberを表示したくなったので、ググった。

sys._getfram()ちゅうやつでできるらしい。例。

In [92]: import sys

In [93]: def hage():
    ...:     print(sys._getframe().f_code.co_name)
    ...:     print(sys._getframe().f_code.co_filename)
    ...:     print(sys._getframe().f_code.co_firstlineno)
    ...:     print(sys._getframe().f_code.co_code)
    ...:     print(sys._getframe().f_lineno)
    ...:     for i in dir(sys._getframe().f_code):
    ...:         print('{} {}'.format(i, getattr(sys._getframe(), i, '-')))
    ...:         

In [94]: hage()
hage
<ipython-input-93-7d9960568d3f>
1
b't\x00t\x01j\x02\x83\x00j\x03j\x04\x83\x01\x01\x00t\x00t\x01j\x02\x83\x00j\x03j\x05\x83\x01\x01\x00t\x00t\x01j\x02\x83\x00j\x03j\x06\x83\x01\x01\x00t\x00t\x01j\x02\x83\x00j\x03j\x07\x83\x01\x01\x00t\x00t\x01j\x02\x83\x00j\x08\x83\x01\x01\x00x2t\tt\x01j\x02\x83\x00j\x03\x83\x01D\x00] }\x00t\x00d\x01j\n|\x00t\x0bt\x01j\x02\x83\x00|\x00d\x02\x83\x03\x83\x02\x83\x01\x01\x00q^W\x00d\x00S\x00'
6
__class__ <class 'frame'>
__delattr__ <method-wrapper '__delattr__' of frame object at 0x00000000071461B8>
__dir__ <built-in method __dir__ of frame object at 0x00000000071461B8>
__doc__ None
__eq__ <method-wrapper '__eq__' of frame object at 0x00000000071461B8>
__format__ <built-in method __format__ of frame object at 0x00000000071461B8>
__ge__ <method-wrapper '__ge__' of frame object at 0x00000000071461B8>
__getattribute__ <method-wrapper '__getattribute__' of frame object at 0x00000000071461B8>
__gt__ <method-wrapper '__gt__' of frame object at 0x00000000071461B8>
__hash__ <method-wrapper '__hash__' of frame object at 0x00000000071461B8>
__init__ <method-wrapper '__init__' of frame object at 0x00000000071461B8>
__init_subclass__ <built-in method __init_subclass__ of type object at 0x000000001DA38550>
__le__ <method-wrapper '__le__' of frame object at 0x00000000071461B8>
__lt__ <method-wrapper '__lt__' of frame object at 0x00000000071461B8>
__ne__ <method-wrapper '__ne__' of frame object at 0x00000000071461B8>
__new__ <built-in method __new__ of type object at 0x000000001DA3C580>
__reduce__ <built-in method __reduce__ of frame object at 0x00000000071461B8>
__reduce_ex__ <built-in method __reduce_ex__ of frame object at 0x00000000071461B8>
__repr__ <method-wrapper '__repr__' of frame object at 0x00000000071461B8>
__setattr__ <method-wrapper '__setattr__' of frame object at 0x00000000071461B8>
__sizeof__ <built-in method __sizeof__ of frame object at 0x00000000071461B8>
__str__ <method-wrapper '__str__' of frame object at 0x00000000071461B8>
__subclasshook__ <built-in method __subclasshook__ of type object at 0x000000001DA38550>
co_argcount -
co_cellvars -
co_code -
co_consts -
co_filename -
co_firstlineno -
co_flags -
co_freevars -
co_kwonlyargcount -
co_lnotab -
co_name -
co_names -
co_nlocals -
co_stacksize -
co_varnames -

他にも、inspectモジュールでもできるらしいが、まあ、これでできたので、良しとする。

参考。
qiita.com

qiita.com

t2y.hatenablog.jp