Absolute imports?

R

Roy Smith

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?

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.
 
C

Chris Angelico

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.

Since absolute imports can be controlled with a future directive, you
can check it out via that module:
_Feature((2, 5, 0, 'alpha', 1), (3, 0, 0, 'alpha', 0), 16384)

Looks like it was held over for 3.0 rather than potentially breaking
stuff across 2.6->2.7.

ChrisA
 
P

Peter Otten

Roy said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top