Identifying Caller

  • Thread starter =?iso-8859-9?Q?Tongu=E7?= Yumruk
  • Start date
?

=?iso-8859-9?Q?Tongu=E7?= Yumruk

Is there a way to identify the caller of a function? For example:

def foo():
print <Caller Functions name>

def bar():
foo()

I want foo to print "bar"... And it will be great if I can also detect
call is came from which module.

Thanks.

--
Love, Respect, Linux
############################################################################
"And the next time you consider complaining that running Lucid Emacs
19.05 via NFS from a remote Linux machine in Paraguay doesn't seem to
get the background colors right, you'll know who to thank."
(By Matt Welsh)
############################################################################
Tonguç Yumruk

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.2 (GNU/Linux)

iD8DBQE/iR6d1xWu4MLSyoYRAoE4AJ4r1+kwxqnFOr+Mu9QOqDGF4Pw6KQCg3Syq
jabkOdMQup66Xymjtux1QXY=
=XtrV
-----END PGP SIGNATURE-----
 
R

Robin Becker

Tonguç said:
Is there a way to identify the caller of a function? For example:

def foo():
print <Caller Functions name>

def bar():
foo()

I want foo to print "bar"... And it will be great if I can also detect
call is came from which module.

Thanks.
try something like this

#############################
def who_called_me(n=0):
import sys
f = sys._getframe(n)
c = f.f_code
return c.co_filename, c.co_name, f.f_lineno

if __name__=='__main__':
def test2():
print 'test2',who_called_me(1)

def test1():
print 'test1',who_called_me(1)
test2()

def test():
print 'test',who_called_me(1)
test1()
test2()

class dingo:
def __init__(self):
self.a = 1
print '__init__',who_called_me(1)
def doit(self):
print 'dingo.doit',who_called_me(1), self.a
def calldoit(self):
print 'dingo.calldoit',who_called_me(1), self.a
self.doit()
test()
def mongo():
print 'mongo', who_called_me(1)
d=dingo()
d.doit()
d.calldoit()
test()
test1()
test2()
mongo()
 
A

Alex Martelli

Tonguç Yumruk said:
Is there a way to identify the caller of a function? For example:

def foo():
print <Caller Functions name>

def bar():
foo()

I want foo to print "bar"... And it will be great if I can also detect
call is came from which module.

See function _getframe in module sys. The frame object that
it returns has many attributes useful for your tasks. In particular,
sys._getframe(1).f_code.co_name should be 'bar' as you require,
and sys._getframe(1).f_globals['__name__'] should be the module
name which you desire.


Alex
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top