View Full Version : importing a lot of modules in python

11 November 2010, 08:38 PM

this is kind of a small problem but I can't seem to find a good solution to it..

I'm trying to import several modules into another module. For example:

import foo
reload (foo)
import foo2
reload (foo2)

I tried looping through them, ie:

modules = [foo, foo2]
for m in modules:
import m
reload (m)

but it tells me that m is not a module. I'm still pretty new to python.. is there a good way to do this?

11 November 2010, 09:12 PM
use __import__ which lets you import using a string name to specify the module to import. You can then assign it into globals() for access:

module = __import__('math', globals(), locals())
globals()['math'] = module

#test it
print math

the import command actually calls the __import__ function, so there's plenty of information on __import__ here:

11 November 2010, 07:53 AM
usually, everybody just states which imports he needs for his module. PyEclipse does a good job adding import statements automatically when you use some class via autocomplete.

If the reload() part is the reason you're doing this... then I'd suggest not doing that.

Fiirst, adding "reload" to your module code causes a lot of problems with reusability. Imagine you'd want to import some 3rd party code and discover that upon import it will reload some of the code you need - this messes up quite a bit.

Solution is... Just write code as you'd normally do, without reloads. Create totally separate utility which reloads EVERYTHING you currently need. Here's where you can automate; i'd suggest loop through currently imported modules (sys.modules dictionary) and just deleting those entries that are your code - easily recognized if you put your code into one package.

Run that utility each time before your test code. *Plan* when you want it. Remember, if you reload twice in one execution, that may cause problems.

This way you can deliver reload-free code after testing, and have an automated reload while you're developing the code.

11 November 2010, 09:53 AM
Agreed, my final code does not have reload calls in it, and as a practice I don't use reload Rarely if im testing in a live environment, and I need to reload to pick up my changes I might.

Though as Uiron mentioned I typically flush my environment, rather than reload.(and only when testing).

import foo, foo2

11 November 2010, 09:33 PM
Thanks everyone! I can see how the reload function could cause problems down the line--since pretty much everything is still in 'testing' it's been ok so far. I'll look into setting up a utility to do it more cleanly from now on tho..

CGTalk Moderation
11 November 2010, 09:33 PM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.