How to determine which method was used in an inheritance heirarchy?
Erik Jones
erik at myemma.com
Mon Jul 16 10:50:32 EDT 2007
On Jul 16, 2007, at 3:37 AM, Gabriel Genellina wrote:
> En Mon, 16 Jul 2007 03:56:18 -0300, Erik Jones <erik at myemma.com>
> escribió:
>
>> Perhaps an even better example of what I'm trying to do would be in
>> order (this is minus any exception handling):
>>
>> import sys
>>
>> def mytrace(frame, event, arg):
>> if event == 'call':
>> func_name = frame.f_code.co_name
>>
>> if func_name in frame.f_locals['self'].__class__.__dict__:
>> print frame.f_locals['self'].__class__.__name__
>> else:
>> for base in frame.f_locals['self'].__class__.__bases__:
>> if func_name in base.__dict__:
>> print base.__name__
>> break
>>
>>
>> class A(object):
>> def __init__(self):
>> pass
>>
>> class B(A):
>> def __init__(self):
>> A.__init__(self)
>>
>> sys.settrace(mytrace)
>> B()
>>
>> This will output:
>>
>> B
>> B
>
> If you don't mind post-processing the results, you can log the
> function
> name and source module (from frame.f_code.co_name and co_filename) and
> current line number (frame.f_lineno). Later, obtaining the class
> name from
> those is a bit tricky (and not even the inspect module does it
> right), but
> perhaps using the tokenizer module, watching for lines that contain
> "class" <name> is enough.
I was afraid of that. I used pretty much that tokenizer trick for a
unit test generator I wrote in php a while back and felt like that
was pretty clunky then.
Erik Jones
Software Developer | Emma®
erik at myemma.com
800.595.4401 or 615.292.5888
615.292.0777 (fax)
Emma helps organizations everywhere communicate & market in style.
Visit us online at http://www.myemma.com
More information about the Python-list
mailing list