bdb: which class?

Stephen J. Turner sjturner at ix.netcom.com
Wed Jan 12 10:01:03 EST 2000


"Zakon, Stuart" wrote:
> So far I am using the following within a subclass of Bdb:
> 
>         def where_am_i (self, frame):
>                 name = frame.f_code.co_name
>                 filename = frame.f_code.co_filename
>                 lineno = frame.f_code.co_firstlineno
>                 self.here_i_am = '%s, %s, %d' % (name, filename, lineno)
> 
> I would like to have the class name for methods of classes which are being
> called but I didn't see it in the documentation for code objects.
> Anybody know if this can be found?

How about the following:

def where_am_i(self, frame):
    from types import InstanceType, MethodType
    code = frame.f_code
    name = code.co_name
    if code.co_argcount:
        arg0 = frame.f_locals[code.co_varnames[0]]
        if type(arg0) is InstanceType:
            attr = getattr(arg0, name, None)
            if attr and \
               type(attr) is MethodType and \
               attr.im_func.func_code is code:
                classname = arg0.__class__.__name__
    ....

If the current frame is for a method invocation, then its corresponding
code object must have at least one argument, and the first named
argument (probably `self', but we can't assume) identifies the class
instance.  This name is then used as an index into the frame's `locals'
dictionary to get the first argument.

Since, however, the frame could also be for a function invocation, we
make sure that (1) the type of the first argument is a class instance,
(2) the instance has an attribute whose name matches the code object's,
(3) the instance attribute is in fact a method, and (4) the method's
underlying code object is the same as the frame's.  If all these are
true, then we get the class name from the instance.

Regards,
Stephen

--
Stephen J. Turner <sjturner at ix.netcom.com>



More information about the Python-list mailing list