Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dynamically get the set of classes from the current python module?

I have a python module that defines a number of classes:

class A(object):
    def __call__(self):
        print "ran a"

class B(object):
    def __call__(self):
        print "ran b"

class C(object):
    def __call__(self):
        print "ran c"

From within the module, how might I add an attribute that gives me all of the classes?

dir() gives me the names of everything from within my module, but I can't seem to figure out how to go from the name of a class to the class itself from within the module.

From outside of the module, I can simply use getattr(mod, 'A'), but I don't have a self kind of module from within the module itself.

This seems pretty obvious. Can someone tell me what I'm missing?

like image 733
Dustin Avatar asked Nov 28 '08 22:11

Dustin


3 Answers

import sys
getattr(sys.modules[__name__], 'A')
like image 131
Igal Serban Avatar answered Sep 28 '22 08:09

Igal Serban


You can smash this into one for statement, but that'd have messy code duplication.

import sys
import types
this_module = sys.modules[__name__]
[x for x in
    [getattr(this_module, x) for x in dir(this_module)]
    if type(x) == types.ClassType]
like image 20
strager Avatar answered Sep 28 '22 08:09

strager


classes = [x for x in globals().values() if isinstance(x, type)]
like image 27
tatwright Avatar answered Sep 28 '22 08:09

tatwright