Return name of caller function?

Jay Loden python at jayloden.com
Tue Jun 26 19:23:00 CEST 2007


Matthew Peter wrote:
> For example, how do I get this to work?
> 
> def func():
>     print "This is", __?__
>     return __caller__
> 
> def echo():
>     print "This is ", __?__
>     return func()
> 
> 
>>>> print echo()
> This is echo
> This is func
> echo

This may not be what you're looking for but here's the solution I ended up with after some help from the list. It's designed for getting the name of an instance method, but in case it applies to your particular situation: 

#!/usr/bin/python

import functools

class TestClass:
  def __init__(self):
    pass

  def __getattr__(self, name):
    try:
      return getattr(self.__class__, name)
    except AttributeError:
      return functools.partial(self.foo, name)

  def foo(self, name, **args):
    print "This is", name

test = TestClass()
test.someMethod()
test.anotherMethod()

Otherwise the inspect module may be the way to go, as Stephen already pointed out (though I must admit it seems a very inelegant route, especially compared to Python's usually clean and clear style). 

-Jay



More information about the Python-list mailing list