Given an instance of some class in Python, it would be useful to be able to determine which line of source code defined each method and property (e.g. to implement 1). For example, given a module ab.py
class A(object): z = 1 q = 2 def y(self): pass def x(self): pass class B(A): q = 4 def x(self): pass def w(self): pass
define a function whither(class_, attribute) returning a tuple containing the filename, class, and line in the source code that defined or subclassed attribute. This means the definition in the class body, not the latest assignment due to overeager dynamism. It’s fine if it returns ‘unknown’ for some attributes.
>>> a = A() >>> b = B() >>> b.spigot = 'brass' >>> whither(a, 'z') ('ab.py', <class 'a.A'>, [line] 2) >>> whither(b, 'q') ('ab.py', <class 'a.B'>, 8) >>> whither(b, 'x') ('ab.py', <class 'a.B'>, 9) >>> whither(b, 'spigot') ('Attribute 'spigot' is a data attribute')
I want to use this while introspecting Plone, where every object has hundreds of methods and it would be really useful to sort through them organized by class and not just alphabetically.
Of course, in Python you can’t always reasonably know, but it would be nice to get good answers in the common case of mostly-static code.
You are looking for the undocumented function
inspect.classify_class_attrs(cls). Pass it a class and it will return a list of tuples('name', 'kind' e.g. 'method' or 'data', defining class, property). If you need information on absolutely everything in a specific instance you’ll have to do additional work.Example: