how to find available classes in a file ?

Ben Finney bignose+hates-spam at benfinney.id.au
Tue Jul 17 03:20:13 EDT 2007


Stef Mientki <S.Mientki-nospam at mailbox.kun.nl> writes:

> I want to have a (dynamically) list of all classes defined in a py-file.
> Is there a way of getting this list, without manually parsing the file ?

    >>> import random
    >>> for name in dir(random):
    ...     obj = getattr(random, name)
    ...     if isinstance(obj, type):
    ...             print "%(name)s is a type" % locals()
    ... 
    Random is a type
    SystemRandom is a type
    WichmannHill is a type
    _BuiltinMethodType is a type
    _MethodType is a type
    >>>

And, since you asked for just getting the list, here's the list of
names:

    >>> [name for (name, obj) in
    ...     [(name, getattr(random, name)) for name in dir(random)]
    ...     if isinstance(obj, type)]
    ['Random', 'SystemRandom', 'WichmannHill', '_BuiltinMethodType', '_MethodType']

Or the list of type objects themselves:

    >>> [obj for obj in
    ...     [getattr(random, name) for name in dir(random)]
    ...     if isinstance(obj, type)]
    [<class 'random.Random'>, <class 'random.SystemRandom'>, <class 'random.WichmannHill'>, <type 'builtin_function_or_method'>, <type 'instancemethod'>]


-- 
 \       "Pinky, are you pondering what I'm pondering?" "Well, I think |
  `\    so, Brain, but I can't memorize a whole opera in Yiddish."  -- |
_o__)                                            _Pinky and The Brain_ |
Ben Finney



More information about the Python-list mailing list