Relative vs Absolute Imports
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.
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.
00:20
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.
00:33
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.
00:44
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, Animals(models.Model)
.
00:59
These will have a name = models.CharField()
.
01:11
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 from models
01:24
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 forms
is.
01:37
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.
01:52
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.
02:08
So for example, as you can see here, these are absolute imports. From the register
module, import models
and import these two different things.
02:17
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.