Refer to function name (newbie ques)

Thomas Jensen spam at ob_scure.dk
Thu Jul 25 11:24:59 EDT 2002


chris ciotti wrote:
> Hi - 
> 
> Is there a way to get the name of the running function?  In a  script
> I'm doing some error checking and I want to be able to name the
> function that screws up.  Something like:

Such error handling is often done using exception handling.
An (not to elegant) example:

--- Python code --
class MyError(Exception):
   pass

def foo():
   try:
     stuff=1
     bar=2
     if stuff != bar:
       raise MyError('Mismatch')

   except MyError, e:
     import sys
     print 'Error: "%s" happened in "%s"' % (
       str(e),
       str(sys.exc_info()[2].tb_frame.f_code.co_name)
     )

foo()
--- Python code end ---

The above code prints:
   Error: "Mismatch" happened in "foo"

The (sys.exc_info()[2].tb_frame.f_code.co_name) part is where the name 
is found.

Links:
* http://www.python.org/doc/current/lib/module-sys.html
* http://www.python.org/doc/current/lib/module-exceptions.html

Also look at asyncore and cgitb, they do some quite advanced error 
reporting.

-- 
Best Regards
Thomas Jensen
(remove underscore in email address to mail me)




More information about the Python-list mailing list