Explore Flask

2.2. Relative imports

Relative imports make life a little easier when developing Flask apps. The premise is simple. Let's say you want to import the User model from the module myapp/models.py. You might think to use the app's package name, i.e. myapp.models. Using relative imports, you would indicate the location of the target module relative to the source. To do this we use a dot notation where the first dot indicates the current directory and each subsequent dot represents the next parent directory. Listing illustrates the diffence in syntax.

# myapp/views.py

# An absolute import gives us the User model
from myapp.models import User

# A relative import does the same thing
from .models import User

The advantage of this method is that the package becomes a heck of a lot more modular. Now you can rename your package and re-use modules from other projects without the need to update the hard-coded import statements.

In my research I came across a Tweet that illustrates the benefit of relative imports.

Just had to rename our whole package. Took 1 second. Package relative imports FTW!

David Beazley, @dabeaz

Note You can read a little more about the syntax for relative imports from this section in PEP 328.