Python - Get class of type from imported module
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,开发者_如何学Python so in this instance, SomeClassA. Is there any way to do this?
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
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)]
精彩评论