AbsoluteRelative Imports

suggest change

In Python 3, PEP 404 changes the way imports work from Python 2. Implicit relative imports are no longer allowed in packages and from ... import * imports are only allowed in module level code.

To achieve Python 3 behavior in Python 2:

For clarification, in Python 2, a module can import the contents of another module located in the same directory as follows:

import foo

Notice the location of foo is ambiguous from the import statement alone. This type of implicit relative import is thus discouraged in favor of explicit relative imports, which look like the following:

from .moduleY import spam
from .moduleY import spam as ham
from . import moduleY
from ..subpackage1 import moduleY
from ..subpackage2.moduleZ import eggs
from ..moduleA import foo
from ...package import bar
from ...sys import path

The dot . allows an explicit declaration of the module location within the directory tree.

More on Relative Imports

Consider some user defined package called shapes. The directory structure is as follows:

shapes
├── __init__.py
|
├── circle.py
|
├── square.py
|
└── triangle.py

circle.py, square.py and triangle.py all import util.py as a module. How will they refer to a module in the same level?

from . import util # use util.PI, util.sq(x), etc

OR

from .util import * #use PI, sq(x), etc to call functions

The . is used for same-level relative imports.

Now, consider an alternate layout of the shapes module:

shapes
├── __init__.py
|
├── circle
│   ├── __init__.py
│   └── circle.py
|
├── square
│   ├── __init__.py
│   └── square.py
|
├── triangle
│   ├── __init__.py
│   ├── triangle.py
|
└── util.py

Now, how will these 3 classes refer to util.py?

from .. import util # use util.PI, util.sq(x), etc

OR

from ..util import * # use PI, sq(x), etc to call functions

The .. is used for parent-level relative imports. Add more .s with number of levels between the parent and child.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Incompatibilities moving from Python 2 to Python 3:
* AbsoluteRelative Imports
* map

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
39 Incompatibilities moving from Python 2 to Python 3
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve