Python equivt of __FILE__ and __LINE__

Jeff Schwab jeff at
Tue Feb 12 19:20:12 CET 2008

Gabriel Genellina wrote:
> En Tue, 12 Feb 2008 14:41:20 -0200, Jeff Schwab <jeff at> 
> escribi�:
>>      def line():
>>              try:
>>                      raise Exception
>>              except:
>>                      return sys.exc_info()[2].tb_frame.f_back.f_lineno
>>      def file():
>>              return inspect.currentframe().f_code.co_filename
> It's not a good idea to shadow the file type; I'd suggest current_file 
> and current_line.
> file() should return inspect.currentframe().f_back.f_code.co_filename, 
> else you're using the filename for file() itself, not the caller's

Both excellent points.

> And why the assymetry? Using try/except might help Jython, but that 
> should be an implementation detail of inspect.currentframe() anyway. 
> line() should just return inspect.currentframe().f_back.f_lineno

I suspect that Alain was just showing two ways to accomplish the same 
end, since he was giving a purely didactic example.  I dumbly copied his 

What about the following?  Should the underscores be omitted from the 
method names, for consistency with inspect?

     import inspect
     import sys

     def currentline():
         return inspect.currentframe().f_back.f_lineno

     def currentfile():
         return inspect.currentframe().f_back.f_code.co_filename

     import srcinfo
     import sys

     debug = '-d' in sys.argv
     # ...
     if debug:
         print('reached %s:%d' %
             (srcinfo.currentfile(), srcinfo.currentline()))

More information about the Python-list mailing list