Finding defining class in a decorator

Ziga Seilnacht ziga.seilnacht at gmail.com
Tue May 9 12:48:25 EDT 2006


lcaamano wrote:
> We have a tracing decorator that automatically logs enter/exits to/from
> functions and methods and it also figures out by itself the function
> call arguments values and the class or module the function/method is
> defined on.  Finding the name of the class where the method we just
> entered was defined in is a bit tricky.

[snipped]

You might find this helpful:

import sys

def tracer(func):
    """
    A decorator that prints the name of the class from which it was
called.

    The name is determined at class creation time. This works
    only in CPython, since it relies on the sys._getframe()
    function. The assumption is that it can only be called
    from a class statement. The name of the class is deduced
    from the code object name.
    """
    classframe = sys._getframe(1)
    print classframe.f_code.co_name
    return func


if __name__ == '__main__':

    # this should print Test1

    class Test1(object):

        @tracer
        def spam(self):
            pass

    # this should print Test2

    class Test2(Test1):

        @tracer
        def spam(self):
            pass


> --
> Luis P Caamano
> Atlanta, GA, USA

Hope this helps,
Ziga




More information about the Python-list mailing list