Absolute imports?

Peter Otten __peter__ at web.de
Sat Feb 15 16:46:31 CET 2014


Roy Smith wrote:

> http://docs.python.org/2/whatsnew/2.5.html says:
> 
> "Once absolute imports are the default, import string will always find
> the standard library¹s version."
> 
> Experimentally, it appears that modules in site-packages are also found
> by absolute imports.  I wouldn't consider site-packages to be part of
> the "standard library".  Can somebody give me a more precise description
> of what absolute import does?

Basically, if module foo.bar contains an `import baz` with relative imports 
python will look for foo.baz before searching for baz in sys.path; with 
absolute imports `from . import baz` will only look for baz in the current 
package while `import baz` will only search sys.path.

> It also says, "This absolute-import behaviour will become the default in
> a future version (probably Python 2.7)", but it appears that 2.7.6 is
> still doing relative by default.

$ tree
.
├── baz.py
└── foo
    ├── bar.py
    ├── baz.py
    └── __init__.py

1 directory, 4 files
$ cat baz.py
print("import is absolute")
$ cat foo/baz.py 
print("import is relative")
$ cat foo/bar.py 
import baz

$ python -c 'import foo.bar'
import is relative
$ python3 -c 'import foo.bar'
import is absolute





More information about the Python-list mailing list