Importing by file name

Chris Angelico rosuav at gmail.com
Sun Nov 24 03:07:38 EST 2013


On Sun, Nov 24, 2013 at 7:00 PM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> The importer mechanism as far as I know only accepts module names, not
> filesystem paths; I believe this is by design.  You could imitate it by
> doing something like this:
>
> import imp
> import sys
>
> mod = imp.new_module('spam')
> exec(open('/path/to/spam.py').read(), mod.__dict__)
> sys.modules['spam'] = mod

That's a bit better than just working with a bare dictionary as I did,
but it's still getting a bit heavy-handed with the details. How is
__main__ imported? Presumably that one, at least, can be loaded from a
specific file. Or is that pure magic?

> Is 'spam' really the appropriate name for this module?  What if there is
> already a different module with the name 'spam'?  Presumably if the module
> is named 'spam' then it should be importable as 'spam', but then why the
> need for the path-based import?  Alternatively, you might name the module
> something like "</path/to/spam.py>", which surely won't collide with
> anything imported by the normal mechanism, but then what if the spam module
> is also imported by normal means?  You would end up with two copies of the
> same module with different names.

The same problem already exists with __main__ - I was hoping to
replicate that, not necessarily to solve all its problems :) I'm okay
with using a fixed name (either "__main__" or something that doesn't
collide with that), for the purposes of experimentation.

I know the recent Pythons give a lot of import power to the script.
But maybe I'm just asking too much, and some of this stuff really is
magical and implemented in C?

ChrisA



More information about the Python-list mailing list