Find function name in function

Sean Ross frobozz_electric at hotmail.com
Tue May 20 11:12:22 EDT 2003


Hi.

"Ilariu Raducan" <lale at fotonation.com> wrote in message
news:5Cqya.14237$pK2.19896 at news.indigo.ie...
> Is it possible to find the function name in that specific function?
> I the following example I want to be able to find what name the user
> used to call the function: XXX, yy, zz
> Is that possible?

Not exactly. You can find the name of the function, 'XXX', but not the name
of the referencer, 'yy' or 'zz', with this:

# credit Alex Martelli, "Python Cookbook" p. 440
def whoami():
    "returns name of calling function"
    import sys
    return sys._getframe(1).f_code.co_name

def XXX():
    print whoami()

XXX()
yy=XXX
yy()
zz=XXX
zz()

This outputs:
XXX
XXX
XXX


Or, you can get the source line where this function is called:

def howamicalled():
    "returns source line where calling function is called"
    import inspect
    return inspect.stack()[2][-2][0].strip()

def XXX():
    print howamicalled()

XXX()
yy=XXX
yy()
zz=XXX
zz()

which outputs:
XXX()
yy()
zz()

This seems useful until you do something like the following:

print "%s %s"%(yy(), zz())

Now, this will output:

print "%s %s"%(yy(), zz())
print "%s %s"%(yy(), zz())

At which point I do not think you can reliably isolate which function was
the one being called. For instance, we can define a new function

def foo():
    pass

and

print "%s %s"%(yy(), foo())

will output:

print "%s %s"%(yy(), foo())

But, which function is a referencer to XXX?

So, the answer to your question is, "No, I don't think so"

Hope this helped,
Sean







More information about the Python-list mailing list