Does __import__ require a module to have a .py suffix?

John Krukoff jkrukoff at ltgc.com
Wed Mar 12 15:17:33 EDT 2008


On Wed, 2008-03-12 at 09:22 -0700, mrstephengross wrote:
> Hi all. I've got a python file called 'foo' (no extension). I want to
> be able to load it as a module, like so:
> 
>   m = __import__('foo')
> 
> However, the interpreter tells me "No module named foo". If I rename
> it foo.py, I can indeed import it. Is the extension required? Is there
> any way to override that requirement?
> 
> Thanks,
> --Steve

I recently solved a similar issue, importing from a string, with this
code:

>>> service = imp.new_module( 'ServiceModule' )
>>> compiled = compile( '''...some code here...''', '<string>', 'exec',
0, 1 )
>>> exec compiled in service.__dict__

You could probably shorten it for your needs by using execfile instead.
If it's not in the current directory, you'll probably run into some
issues with further imports not working as expected unless you set the
names/paths right.

-- 
John Krukoff <jkrukoff at ltgc.com>
Land Title Guarantee Company




More information about the Python-list mailing list