Determining caller's file and line number

D

David Abrahams

Is there any way to determine the file and line number (if any) of a
method's invocation from within its body?

Many Thanks in advance,

Dave
 
J

Jean Brouwers

Here is one example:

<pre>

from traceback import extract_stack as tb_extract_stack,

def caller(up=0):
'''Get file name, line number, function name and
source text of the caller's caller as 4-tuple:
(file, line, func, text).

The optional argument 'up' allows retrieval of
a caller further back up into the call stack.

Note, the source text may be None and function
name may be '?' in the returned result. In
Python 2.3+ the file name may be an absolute
path.
'''
try: # just get a few frames
f = tb_extract_stack(limit=up+2)
if f:
return f[0]
except:
pass
# running with psyco?
return ('', 0, '', None)

</pre>

/Jean Brouwers
ProphICy Semiconductor, Inc.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top