Go back to post Create new comment

RSS Be notified of new comments on this post with the RSS feed for this post.

#

This is nice. If I where to reload(module) after changing the contents of filename, what would happen? Presumably I would have to re-run CreateModule to re-exec the file contents. But If I re-initialised variable holding the old module with the new (modified) module, would all the code based on that module update? classes initialised from the module would need to be re-initialised, wouldn't they?

#

It would depend greatly on what you had in your module. If your module had no code ran by default that changes global state, then it should be safe just to re-execfile on the module object.

However if you're removing variable/class/function/etc names from your module then this wont be reflected.

Frankly, the best way is just to call CreateNewModule again. Otherwise you have to worry about just what exact changes you're reloading and to what.

Interestingly you can load multiple module files into the same virtual module object by executing execfile(filename, module.__dict__, module.__dict__) multiple times.

Let's say you had a file called ModuleA.py:

# Filename: ModuleA.py
def FuncA():
    print "I am function A"

And a file called ModuleB.py:

# Filename: ModuleB.py
def FuncB():
    print "I am function B"

You could modify CreateNewModule to take in multiple filenames like so:

def CreateNewModuleFromList(name, filenames):
    module = types.ModuleType(name)
    for filename in filenames:
        execfile(filename, module.__dict__, module.__dict__)
    return module

Example usage:

>>> m = CreateNewModuleFromList("MULTIMODULE", ["ModuleA.py", "ModuleB.py"])
>>> m
<module 'MULTIMODULE' (built-in)>
>>> dir(m)
['FuncA', 'FuncB', '__builtins__', '__doc__', '__name__']
>>> m.FuncA()
I am function A
>>> m.FuncB()
I am function B
>>>

Note: If ModuleB.py contained something called FuncA then that would overwrite the previous implementation of FuncA that was defined in ModuleA.py.

Go back to post

Create a new comment

Go to the top

You can use a restricted version of markdown formatting here. You can use the toolbar above the text field to make this more painless. For more information about markdown please refer to the markdown cheatsheet.

For post: Dynamically importing Python modules by filename
Your name:
Your email (optional):
Your website (optional):
 
 
 

A preview of your comment:

Powered by Debian, Guinness, and excessive quantities of caffeine and sugar.