I’m trying to dynamically load modules I’ve created.
Right now this works properly:
import structures.index
But if I try the same thing by importing it dynamically, it fails.
struct = __import__('structures.index')
Error supplied is:
Error ('No module named structures.index',)
Any ideas why?
Edit: When using full scope (it sort of works?):
struct = __import__('neoform.structures.index')
This doesn’t throw any errors, however, it isn’t loading the index module, it’s loading the ‘neoform’ module instead.
The result of ‘struct’ is:
<module 'neoform' from '/neoform/__init__.py'>
Also, as a side question, how can I then instantiate a class within a dynamically loaded module? (assuming all the modules contain a common class name).
Edit: Solution: (thanks coonj & Rick) This ended up being what worked. Not sure why (yet), but the fromlist had to be something ‘anything apparently, since it worked when I put the letter ‘a’ as a value (strange, given that the file only had 1 class in it).
def get_struct_module(self, name): try: return = __import__('neoform.structures.' + name, fromlist='*') except ImportError, e: self.out.add('Could not load struct: neoform.structure.' + name + '\n\n' + 'Error ' + str(e.args))
I’m not sure what ‘it fails’ means, so I’ll just mention that
__import__('structures.index')should, in fact, work, but it doesn’t assign the module name in the current scope. To do that (and then use a class in the dynamically imported module), you’ll have to use:The complete details on
__import__are available here.Edit: (based on question edit)
To import
neoform.structures.index, and return theindexmodule, you would do the following:So if you have a list of package names
packages, you can import theirindexmodules and instantiate someMyClassclass for each using the following code: