Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Get class of type from imported module

Tags:

python

I am trying to import a class from a file with a dynamic name. Here is my file importer:

def get_channel_module(app, method):
    mod_name = 'channel.%s.%s' % (app, method)
    module = __import__(mod_name, globals(), locals(), [method])
    return module

This imports the specific python file, for example, some_file.py, which looks like this:

class SomeClassA(BaseClass):
    def __init__(self, *args, **kwargs):
        return

class SomeClassB():
    def __init__(self, *args, **kwargs):
        return

What I want to do is return only the class which extends BaseClass from the imported file, so in this instance, SomeClassA. Is there any way to do this?

like image 273
Hanpan Avatar asked May 23 '11 09:05

Hanpan


2 Answers

You can do this by inspecting the symbols in your module with issubclass:

def get_subclass(module, base_class):
    for name in dir(module):
        obj = getattr(module, name)
        try:
            if issubclass(obj, base_class):
                return obj
        except TypeError:  # If 'obj' is not a class
            pass
    return None
like image 197
Ferdinand Beyer Avatar answered Oct 03 '22 16:10

Ferdinand Beyer


Once you have your module imported, iterate it's namespace looking for class objects that are subclasses of BaseClass.

klasses = [c for c in module.__dict__.values() if isinstance(c, type)]
base_subclasses = [c for c in klasses if issubclass(c, BaseClass]
## or as a single list comprehension
base_subclasses = [c for c in module.__dict__.values() if isinstance(c, type) and issubclass(c, BaseClass)]
like image 39
Rob Cowie Avatar answered Oct 03 '22 18:10

Rob Cowie