Mailing List Archive

function which knows who has called it.
Is if possible in Python to have a function that prints the name
of the function that called it. (I'm thinking of using this in
some debugging code I want to write).

--
Phil Hunt....philh@vision25.demon.co.uk
function which knows who has called it. [ In reply to ]
On Mon, 16 Aug 99 22:12:49 GMT, philh@vision25.demon.co.uk (Phil Hunt) wrote:

> Is if possible in Python to have a function that prints the name
> of the function that called it. (I'm thinking of using this in
> some debugging code I want to write).

Yes, it's possible, take a look at the traceback module. I use this piece of
code to print the name of function that invokes the 'should' function:

import traceback

def should (condition, message=None):
if (not condition):
methodName = traceback.extract_stack()[-2][2]
fail ("%s: %s" % (methodName, message))


Greetings,
--
Ovidiu Predescu <ovidiu@cup.hp.com>
http://andromeda.cup.hp.com/ (inside HP's firewall only)
http://www.geocities.com/SiliconValley/Monitor/7464/
function which knows who has called it. [ In reply to ]
You can get the callers name from this also.
But that's up to you.

def myDirExcept(howFarBack):
"""
Get the directory of the module running at "howfarBack "
in the stack frames
This value is compiled into the .pyc file
This can be a problem.
Name will change depending on where python was run from
when the pyc file was created
Unix can store a relative path
Windows stores an absolute path
"""
try:
raise ZeroDivisionError
except ZeroDivisionError:
f = sys.exc_info()[2].tb_frame

for i in range(howFarBack):
f = f.f_back

t = f.f_code
fname = t.co_filename
p = string.split(fname, os.sep)
fname = string.join(p[:-1], os.sep)
return fname


--
--Darrell
Phil Hunt <philh@vision25.demon.co.uk> wrote in message
news:934841569snz@vision25.demon.co.uk...
>
> Is if possible in Python to have a function that prints the name
> of the function that called it. (I'm thinking of using this in
> some debugging code I want to write).
>
> --
> Phil Hunt....philh@vision25.demon.co.uk
>
function which knows who has called it. [ In reply to ]
Phil Hunt <philh@vision25.demon.co.uk> wrote:

: Is if possible in Python to have a function that prints the name
: of the function that called it. (I'm thinking of using this in
: some debugging code I want to write).

The information is captured in the frames in the traceback.

def you_rang():
import sys
try:
raise RuntimeError
except RuntimeError:
exc, val, tb = sys.exc_info()
frame = tb.tb_frame.f_back
del exc, val, tb
try:
return frame.f_back.f_code.co_name
except AttributeError: # called from the top
return None

def f():
WhoCalledMe = you_rang()

-Arcege