[Tutor] listing classes

Dave Kuhlman dkuhlman at rexx.com
Wed May 21 02:01:26 CEST 2008


On Tue, May 20, 2008 at 01:48:03PM -0400, Kent Johnson wrote:
> 
> Note: types.ClassObj is the type of old-style classes. The OP used
> new-style classes which are of type type. Using type(A) for the
> comparison means it will work with either kind of classes as long as
> they are the same. You could also use inspect.isclass() to decide if
> it is a class.

Using the inspect module sounds like a good suggestion to me.

I'm wondering why we don't use the inspect module all the way. 
Here is a bit of code:

    import inspect

    # Import the module containing the classes we want to list.
    import test_inspect_data

    def test():
        outer_classes = inspect.getmembers(test_inspect_data, inspect.isclass)
        print outer_classes
        for name, class_ in outer_classes:
            inner_classes = inspect.getmembers(class_, inspect.isclass)
            print inner_classes

    if __name__ == '__main__':
        test()

Which prints out:

    [('A', <class 'test_inspect_data.A'>)]
    [('B', <class 'test_inspect_data.B'>),
        ('C', <class 'test_inspect_data.C'>),
        ('__class__', <type 'type'>)]


- Dave


-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman


More information about the Tutor mailing list