Ok here is your solution :
For Importing the module using name as string:
__import__(modulename, globals(), locals(), ['*'])
Load the class from the module path:
cls = getattr(sys.modules[modulename], classname)
Directory structure:
:/tmp/dynamic_import:~ ls
chocolate fruit need_dynamic.py
:/tmp/dynamic_import:~
need_dynamic.py
fruit
|-- strawberry.py
|-- orange.py
chocolate
|-- cadbury.py
|-- kitkat.py
Here is one of the module inside fruit, i name the class name with respect to module name with initials caps:
:/tmp/dynamic_import:~ cat orange.py
class Orange(object):
def say(self):
return "Say cheese from class: %s" % __name__
:/tmp/dynamic_import:~
Here is your main script:
#!/usr/bin/env python
import os
import sys
import inspect
def load_modules_from_path(path):
"""
Import all modules from the given directory
"""
# Check and fix the path
if path[-1:] != '/':
path += '/'
# Get a list of files in the directory, if the directory exists
if not os.path.exists(path):
raise OSError("Directory does not exist: %s" % path)
# Add path to the system path
sys.path.append(path)
# Load all the files in path
for f in os.listdir(path):
# Ignore anything that isn't a .py file
if len(f) > 3 and f[-3:] == '.py':
modname = f[:-3]
# Import the module
__import__(modname, globals(), locals(), ['*'])
def load_class_from_name(fqcn):
# fqcn = fully qualified classname
# Break apart fqcn to get module and classname
paths = fqcn.split('.')
modulename = '.'.join(paths[:-1])
classname = paths[-1]
# Import the module
__import__(modulename, globals(), locals(), ['*'])
# Get the class
cls = getattr(sys.modules[modulename], classname)
# Check cls
if not inspect.isclass(cls):
raise TypeError("%s is not a class" % fqcn)
# Return class
return cls
def main():
food_list = ['fruit', 'chocolate']
subfood_list = [['strawberry', 'orange'],['cadbury', 'kitkat']]
# show food list for users to select.
for i in xrange(len(food_list)):
print '%d: %s' % (i, food_list[i])
food_index = int(raw_input('Choose one: '))
for i in xrange(len(subfood_list[food_index])):
print '%d: %s' % (i, subfood_list[food_index][i])
subfood_index = int(raw_input('Chose one: '))
pkg = food_list[food_index]
module = subfood_list[food_index][subfood_index]
class_name = module.title()
load_modules_from_path(pkg)
new_class = load_class_from_name('%s.%s' % (module, class_name))
# instantiation
obj = new_class()
print obj.say()
if __name__ == '__main__': main()
Here is the output:
:/tmp/dynamic_import:~ python need_dynamic.py
0: fruit
1: chocolate
Choose one: 0
0: strawberry
1: orange
Chose one: 0
Say cheese from class: strawberry
:/tmp/dynamic_import:~ python need_dynamic.py
0: fruit
1: chocolate
Choose one: 1
0: cadbury
1: kitkat
Chose one: 0
Say cheese from class: cadbury
:/tmp/dynamic_import:~
Please let me know if that works.