Alex Rivera | Logout

Python: How to retrieve class information from a 'frame' object?

Asked 2010-02-04T21:38:09.087
27

Is it possible to retrieve any class information from a frame object? I know how to get the file (frame.f_code.co_filename), function (frame.f_code.co_name) and line number (frame.f_lineno), but would like to be able to also get the name of the class of the active object instance of the frame (or None if not in an instance).

Edit
Report

1 Answer

7

This is a bit shorter, but does about the same. Returns None if class name not available.

def get_class_name():
    f = sys._getframe(1)

    try:
        class_name = f.f_locals['self'].__class__.__name__
    except KeyError:
        class_name = None

    return class_name
answered 2010-03-30T11:14:08.853

Your Answer