This is a quick one-liner to produce the filename and line number of the caller of the current function.
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))
      
    Tags: _getframe
  
  
      
Download
Copy to clipboard