Return name of caller function?

Jay Loden python at
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: 


import functools

class TestClass:
  def __init__(self):

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

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

test = TestClass()

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). 


More information about the Python-list mailing list