Python equivt of __FILE__ and __LINE__

Jeff Schwab jeff at
Tue Feb 12 17:41:20 CET 2008

alain wrote:
> On Feb 11, 10:58 am, "Bill Davy" <B... at> wrote:
>> Writing a quick and dirty assembler and want to give the user the location
>> of an error.  The "assembly language" is Python.  If the user wants to
>> generat some object code they write something  like:
>> Label(LoopLable)
>>     Load(R4)
>>     Dec()
>>     JNZ(LoopLabel)
>> I can use Python to do all the expression evalutaion, conversion from Python
>> FP to target FP, include files, macros (done as function definitions).  The
>> functions like Load() generate the approproyte object code.
>> So, for example, when a label is defined or referenced, I save the File,Line
>> so if there is not exactly one defintion or no references, I can report the
>> file location(s) to be considered.  In the example, I would want to report
>> that LoopLable is not referenced, and LoopLabel is not defined.
>> TIA,
>>     Bill
>> PSwww.SynectixLtd.comis not relevant
> 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

That's awesome.  It's easy to see how these and other 
'preprocessor-like' constructs could be wrapped into a convenient 
module.  But the leading and trailing double-underscores, and the 
all-caps function names, seem very un-python.  (It's not really going to 
look like C, anyway, since the client code will need parentheses after 
the pseudo-macro names.)  What would be more pythonic?  Maybe something 
like this?

     import inspect
     import sys

     def line():
                     raise Exception
                     return sys.exc_info()[2].tb_frame.f_back.f_lineno
     def file():
             return inspect.currentframe().f_code.co_filename

     if __name__ == '__main__':
             print "%s: %d" % (file(), line())

     import srcinfo

     if __name__ == '__main__':
                     # Whatever.
                     raise Exception, "hello"
             except Exception, x:
                     print ('warning: %s: %d: %s' %
                             (srcinfo.file(), srcinfo.line(), x))

More information about the Python-list mailing list