This lesson shows the difference between relative and absolute imports. You’ll learn about the differences in the way relative imports work in Python 2 and in Python 3.
Relative vs Absolute Imports
Let’s take a quick look at our
forms file. As you can see, it goes into the
register module and goes into the
models file and imports a couple of models. Okay, no big deal. It’s very simple, very straightforward.
The way you know something is a module is if it has its own
__init__.py. Modules are generally folders with
__init__.py with Python code under them. So let’s say, for example, we had a
models file here.
import Animals, and then we could save and create
Animals, we’d have all the things that we could do to
Animals. Now, this is what they call a relative import. It’s relative to where the
So when it goes to look to see where
models is, it goes, “Okay, I’m here, here is where
models is.” Now, that’s what you’d call an implicit relative import. It’s implicitly saying, “It’s the one that’s next to me.” Now, in Python 3, that is no longer allowed.
What you have to do is do this. You have to say “In this directory, the
models file, import
Animals.” And that is the difference between an implicit relative import and an explicit relative import, or absolute imports, which are the actual path to the particular thing that you want to import.
Become a Member to join the conversation.