Labels

new blog 2.0

2011/03/24

Python exec module in namespace, an importless import.

The following code demonstrates how to import a Python module into a namespace if the module file does not end with ".py" extension, contains dots or the filename is established during execution. It might be useful for unit testing of scripts of which path is known but which can't be imported directly in the testing module.

I assume that module's name is "module.filename.py.txt", the content follows.
# module.filename.py.txt
def hello():
    for i in range(3):
       print 'oO',
    print

The interactive interpreter:
Python 2.6.5 (r265:79063, Jun  3 2010, 14:39:13)
[GCC 4.1.2 20090703] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Module(object):
...     """Module object."""
...     def __init__(self, ns_dict):
...         """Populate the module."""
...         self.__dict__ = ns_dict
...
>>> mod_filename = 'module.filename.py.txt'
>>> mod_ns_alias = 'mymodule'
>>> source = open(mod_filename).read()
>>> module_code = compile(source, mod_filename, 'exec')
>>> mod_ns = {}
>>> exec module_code in mod_ns
>>> exec('%s = Module(mod_ns)' % mod_ns_alias)
>>>
>>> mymodule.hello()
oO oO oO
>>>

No comments: