Absolute imports?

Ben Finney ben+python at benfinney.id.au
Sat Jan 8 16:53:18 EST 2011


Roy Smith <roy at panix.com> writes:

> If I have an absolute path to a file (i.e. '/home/roy/foo.py'), is
> there a way to import that as a module WITHOUT modifying sys.path? I'm
> using Python 2.6.

Importing a module with ‘import’ is done by using the module's name,
which is only *incidentally* related to its filesystem path.

What is the problem you're trying to solve? It is likely we can suggest
a better solution.

> I've read PEP 328, and don't really understand how the absolute
> imports it's talking about are supposed to work. Should I be using
> imp.load_source()?

PEP 328 introduces a distinction between absolute imports and relative
imports. Before the implementation of PEP 328, it was impossible to
distinguish in the ‘import’ statement whether the import would be
absolute (i.e., from the directories listed in ‘sys.path’) or relative
(i.e., from the directory housing the current module).

I hope that clarifies. If you describe what you're trying to do and why
you want a different import behaviour, the answers might be more
directed to your actual situation.

-- 
 \        “Spam will be a thing of the past in two years' time.” —Bill |
  `\                                                 Gates, 2004-01-24 |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list