Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #60354
| References | <CAPTjJmqhiyT9zVHFRyKH0UwhdhFgZxA1rcbarChePMyfK7dDTA@mail.gmail.com> <CALwzidmqKkpuugv2zvu-8RpoVZF899G2Hpdmd_kVn8a33WMWFw@mail.gmail.com> |
|---|---|
| Date | 2013-11-24 19:07 +1100 |
| Subject | Re: Importing by file name |
| From | Chris Angelico <rosuav@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.3119.1385280468.18130.python-list@python.org> (permalink) |
On Sun, Nov 24, 2013 at 7:00 PM, Ian Kelly <ian.g.kelly@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
Back to comp.lang.python | Previous | Next — Next in thread | Find similar | Unroll thread
Re: Importing by file name Chris Angelico <rosuav@gmail.com> - 2013-11-24 19:07 +1100
Re: Importing by file name Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-11-24 14:15 +0000
Re: Importing by file name Chris Angelico <rosuav@gmail.com> - 2013-11-25 01:25 +1100
Re: Importing by file name Mark Lawrence <breamoreboy@yahoo.co.uk> - 2013-11-24 16:30 +0000
csiph-web