Python Relative Imports

From Exterior Memory
Revision as of 00:02, 23 March 2012 by MacFreek (Talk | contribs) (Relative imports in non-packages)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

PEP 0008:

Relative imports for intra-package imports are highly discouraged. Always use the absolute package path for all imports. Even now that PEP 328 is fully implemented in Python 2.5, its style of explicit relative imports is actively discouraged; absolute imports are more portable and usually more readable.

absolute import:

import package     # searches sys.path only

implicit relative import:

import siblingmodule

explicit relative import:

from . import siblingmodule   # use . or .. to explicitly signify relative path


In code snippets: use absolute imports

import package
from package import module

Within modules: use explicit relative imports

from . import siblingmodule

Relative imports in non-packages

from . import module2

If the above line raises this error:

Attempted relative import in non-package

You are attempting to import another python module from the same directory as your script. Apparently, you have just written that other file and that is a great piece of software that can be used a stand-alone module. Congrats.

The solution to fix this depends on where the error occurs.

If it is a script (thus has a shebang #!/usr/bin/env python on top of the file), you should use an absolute import:

import module2

If it is another module, than you need to turn your scripts into a package. A package looks like the following file structure:

-+ package

The file can be empty.

I do not recommend to change the os.path variable.