Finding the name of a class

Ziga Seilnacht ziga.seilnacht at gmail.com
Tue Aug 1 12:39:02 EDT 2006


Kirk Strauser wrote:
[snip]
> OK, now for the good stuff.  In the code below, how can I find the name of
> the class that 'bar' belongs to:
>
> >>> class Foo(object):
> ...     def bar(self):
> ...             pass
> ...
> >>> b = Foo.bar

>>> print b.im_class.__name__
Foo


But if you are writing a decorator, you can use this code:

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


Hope this helps,
Ziga




More information about the Python-list mailing list