Newbie question: python doesn't search the cwd for my module

Ben Finney bignose+hates-spam at benfinney.id.au
Tue Oct 3 09:45:48 EDT 2006


izak marais <izakmarais at yahoo.com> writes:

> I want to import a module I wrote to use it in a script. But, it is
> not in the same directory as the script I want to import it into.

I can think of two sensible solutions.

One is to change the 'sys.path' list to include the directory where
you want Python to look for your module. This has the advantage that
it will work on all current versions of Python. It has the
disadvantage that modules with the same name in different directories
are not easy to differentiate.

    import sys
    sys.path.append("/path/to/the/directory")
    import spam

The other way is to use absolute imports to be specific about where
the module should be imported from. This has the advantage that at
most one module will match the requested name for a given import. It
has the disadvantage of being a fairly new feature, introduced in
Python 2.5.

    from __future__ import absolute_import
    from ...path.to.the.directory import spam

See here for more information on absolute imports:

    <URL:http://docs.python.org/whatsnew/pep-328.html>
    <URL:http://www.python.org/peps/pep-0328.html>

-- 
 \       "I believe in making the world safe for our children, but not |
  `\    our children's children, because I don't think children should |
_o__)                                  be having sex."  -- Jack Handey |
Ben Finney




More information about the Python-list mailing list