How can I programmatically find the name of a method from within that method?

faulkner faulkner891 at gmail.com
Wed Aug 8 23:23:26 EDT 2007


On Aug 8, 10:43 pm, faulkner <faulkner... at gmail.com> wrote:
> On Aug 8, 12:45 am, kj7ny <kj... at nakore.com> wrote:
>
> > Is there a way that I can programmatically find the name of a method I
> > have created from within that method?  I would like to be able to log
> > a message from within that method (def) and I would like to include
> > the name of the method from which it was written without having to
> > hard-code that value in every message string.  While we're at it, is
> > there a way to programmatically get the name of the class and the
> > module while I'm at it?
>
> > Thanks,
>
> def foo():
>     print sys._getframe(0).f_code.co_name
>
> most of the darkest magic of python is in the frames returned by
> sys._getframe.

sorry for the double-post. i forgot to answer the rest of the
question.

class a:
    def b(self, *a):
        print sys._getframe(0).f_code.co_name
        print self.__class__.__name__
        print getattr(self,
sys._getframe(0).f_code.co_name).im_class.__name__
        print self.__class__.__module__

def log(f):
    def newf(*a, **kw):
        if a and f.func_code.co_varnames[0] == 'self': print '%s.%s.%s
%r %r' % (a[0].__class__.__module__, a[0].__class__.__name__,
f.func_name, a, kw)
        else: print '%s.%s %r %r' % (f.func_globals['__name__'],
f.func_name, a, kw)
        f(*a, **kw)
    newf.__name__ = f.__name__
    newf.__doc__ = f.__doc__
    return newf

you can find more interesting attributes of frame and function objects
using the builtin dir function.




More information about the Python-list mailing list