bdb: which class?

Stuart Zakon sjz18 at yahoo.com
Wed Jan 12 11:44:17 EST 2000


"stephen j. turner" <sjturne- at ix.netcom.com> wrote: 

> 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.

My gosh! I was afraid it was going to be that complicated!
If I had any spare time I would look into why there couldn't just be the
following assignment to get the class:

class_name = frame.f_code.co_class_name

Then you could check to see if it was 'None' to indicate that the method is not
on a class but on a module.

Regards,
Stuart
__________________________________________________
Do You Yahoo!?
Talk to your friends online with Yahoo! Messenger.
http://im.yahoo.com




More information about the Python-list mailing list