0

Can pdb print from which base class did the derived class inherit a particular method from?

import pdb
class A():
    def funct(self):
         print 3

class B():
    def funct(self):
         print 6

class C(A, B):
    pass

b = B();
print b.funct()

===================================

☺ python a.py
3
None

======================================

python -m pdb a.py
(Pdb) p c.funct
<bound method C.funct of <__main__.C instance at 0x102154440>>

Is there a way to get from which base class, the derived class C inherited the funct method?

  • In fact pdb has nothing to do with this. You can introspect Python objects the same way in any context. All pdb gets you (for the most part), is an easy way to move up and down the call stack, as well as set breakpoints. But everything you can inspect in pdb you can inspect without it too. It doesn't make most introspection patterns any different. – Iguananaut Oct 25 '17 at 23:19

1 Answers1

1

You have to instropect that yourself.

You can put the snipped bellow in a utility function, but the idea is: retrieve the class, from the class, iterate over the __mro__ attribute, and in each class there, check if the desired function or attribute is on its __dict__:

print(list(cls for cls in b.__class__.__mro__ if "funct" in cls.__dict__))

(You know "pdb" has nothing to do with that - and that Python usually can work in an interactive mode, right? PDB is just one way of getting into the interacitive mode, albeit one with poor resources if compared with Python shells like ipython.)

As a second note: I don't know what you are doing, but you really should be trying to do that in Python 3.x, not Python 2.

jsbueno
  • 99,910
  • 10
  • 151
  • 209