You're not doing anything to load the modules, you're just creating and running empty modules.
curr_module = imp.new_module(item)
curr_module.run()
From the docs says:
imp.new_module
(name)
Return a new empty module object called name. This object is not inserted in sys.modules.
So, this is effectively the same as if you'd written this:
curr_module = types.ModuleType(item)
curr_module.run()
The reason you get ['__ doc __ ', ' __ name __ ', '__ package __ ']
(although I'm pretty sure you actually get ['__doc__ ', '__name__', '__package__']
without all those extra spaces) is that those attributes exist even on an empty module.
The example code that you copied this from is trying to do something completely different. The whole point of that question is how to create a module out of a string of source code, instead of the normal way. Which you do (in 2.x) by creating a new empty module, then doing an exec
against that module's globals. The exec
is the reason the module ends up not being empty, and you're not doing anything similar.
You're also giving the module an invalid name, like Brd1.py
instead of Brd1
.
If you want to actually load the modules, look at the Examples:
fp, pathname, description = imp.find_module(name)
curr_module = imp.load_module(name, fp, pathname, description)
# …
Of course you don't want to load it by normal search, but by pathname. You could pass a path
argument to find_module
:
name = os.path.splitext(item)[0]
fp, pathname, description = imp.find_module(name, 'boards')
… or just load it directly:
name = os.path.splitext(item)[0]
pathname = os.path.join("boards", item)
desc = [s for s in imp.get_suffixes if s[0] == '.py']
with open(pathname) as f:
curr_module = imp.load_module(name, f, pathname, desc)
You might also want to put the module in sys.modules
. Or you might not. (The example doesn't, because it's simulating the effects of the __import__
function.) If so:
sys.modules[name] = curr_module
You also might want to do the sys.modules
check, as in the example. If you do the check, trying to import the same file twice will use the cached version the second time, as if you'd done a normal import
; if you don't, it will be similar to calling reload
:
try:
curr_module = sys.modules[name]
except KeyError:
# the logic above to find and load curr_module