Welcome, guest | Sign In | My Account | Store | Cart

This is a quick one-liner to produce the filename and line number of the caller of the current function.

Python, 1 line
1
'{0.f_code.co_filename}:{0.f_lineno}'.format(sys._getframe(1))

This is useful for debugging and logging. It also nicely demonstrates the attribute access feature of the .format() method format string. If you wrap it in a function change the argument to _getframe() to 2.

This line reproduces the format used by exception tracebacks:

'File "{0.f_code.co_filename}", line {0.f_lineno}, in {0.f_code.co_name}'.format(sys._getframe(1))

1 comment

Oren Tirosh 8 years, 3 months ago  # | flag

The fork seems identical to the source. Is there anything you wanted to add?