Absolute imports?

Ben Finney ben+python at benfinney.id.au
Mon Jan 10 18:00:28 EST 2011


Roy Smith <roy at panix.com> writes:

>  Ben Finney <ben+python at benfinney.id.au> wrote:
> > What is the problem you're trying to solve? It is likely we can
> > suggest a better solution.
>
> Well, the problem I'm trying to solve is that I have an absolute
> pathname to a python source file that I want to import as a module :-)

And then have it available in the code under what name?

It is important to realise that ‘import’ does many things. Among the
many things it does (see the Python documentation for more) it executes
the code within a namespace, and then binds that namespace to a name
that is specified in the ‘import’ statement.

The filesystem path (if any!) is derived from the name that the module
will be bound to within the code. That'w why the indirection of
‘sys.path’ is necessary: it keeps the mapping between module names and
filesystem paths.

> The best I can describe how to find the location of the config file is, 
> "Work your way up the directory tree from where you are now, (i.e. 
> following '..' links) until you get to the top level of the project, 
> then from there, it's ./code/configs/autogen/config.py."

One way to keep the import mechanism working with that situation would
be to:

* compute the path:   ‘config_dir_path = your_algorithm_above()’
* add the path to the search list:  ‘sys.path.append(config_dir_path)’
* import the config module:  ‘import config’

The module is then available under the name ‘config’.

> It's reasonably straight-forward to figure out that absolute path,
> starting from sys.argv[0] and using the tools in os.path. Now I need
> to import the file, given that I know its absolute pathname. It looks
> like imp.load_source() does what I want, I'm just wondering if there's
> a cleaner way.

I think ‘imp.load_source’ is not as clean as the steps I describe above,
given the rest of the ‘import’ job that needs to be done.

Given that modules in Python form a namespace hierarchy, it's unusual
and discouraged to import files from arbitrary parts of the filesystem.

-- 
 \     “I must say that I find television very educational. The minute |
  `\       somebody turns it on, I go to the library and read a book.” |
_o__)                                                    —Groucho Marx |
Ben Finney



More information about the Python-list mailing list