Search code examples
pythonintrospectionpython-datamodel

Python introspection: How to get an 'unsorted' list of object attributes?


The following code

import types
class A:
    class D:
        pass
    class C:
        pass
for d in dir(A):
    if type(eval('A.'+d)) is types.ClassType:
        print d

outputs

C
D

How do I get it to output in the order in which these classes were defined in the code? I.e.

D
C

Is there any way other than using inspect.getsource(A) and parsing that?


Solution

  • The inspect module also has the findsource function. It returns a tuple of source lines and line number where the object is defined.

    >>> import inspect
    >>> import StringIO
    >>> inspect.findsource(StringIO.StringIO)[1]
    41
    >>>
    

    The findsource function actually searches trough the source file and looks for likely candidates if it is given a class-object.

    Given a method-, function-, traceback-, frame-, or code-object, it simply looks at the co_firstlineno attribute of the (contained) code-object.