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
00:00 The next thing I want to look into is relative imports and absolute imports. Now, in Python 3, implicit relative imports and packages are no longer available.
00:10 You are only allowed to have absolute imports and explicit relative imports are supported. So, there’s a slight nuance there. I’m going to go on to explain that.
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.
We’ll call this
models.py, and we’re going to save that. Let’s say we have some things here. Let’s quickly define one,
These will have a
name = models.CharField().
import models, basically just animals with names. So, let’s say we wanted to import that from our
forms file. So it’s in the same directory, so we’d go
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.
So for example, as you can see here, these are absolute imports. From the
register module, import
models and import these two different things.
So, that’s a slight nuance that you need to keep an eye out for, because if you don’t, what happens is it goes to the path looking for which is the first
models it hits.
02:25 If it hits multiple ones there, it causes problems and then create issues, so be as explicit as you can, as much as you can.
Become a Member to join the conversation.