File: find_class.py

package info (click to toggle)
python-coverage 6.5.0%2Bdfsg1-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 3,580 kB
  • sloc: python: 25,471; ansic: 1,152; javascript: 1,104; makefile: 253; sh: 107; xml: 48
file content (40 lines) | stat: -rw-r--r-- 950 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Parent:
    def meth(self):
        print("METH")

class Child(Parent):
    pass

def trace(frame, event, args):
    # Thanks to Aleksi Torhamo for code and idea.
    co = frame.f_code
    fname = co.co_name
    if not co.co_varnames:
        return
    locs = frame.f_locals
    first_arg = co.co_varnames[0]
    if co.co_argcount:
        self = locs[first_arg]
    elif co.co_flags & 0x04:    # *args syntax
        self = locs[first_arg][0]
    else:
        return

    func = getattr(self, fname).__func__
    if hasattr(func, '__qualname__'):
        qname = func.__qualname__
    else:
        for cls in self.__class__.__mro__:
            f = cls.__dict__.get(fname, None)
            if f is None:
                continue
            if f is func:
                qname = cls.__name__ + "." + fname
                break
    print(f"{event}: {self}.{fname} {qname}")
    return trace

import sys
sys.settrace(trace)

Child().meth()