Using Import Statements
00:00 We’ll start talking about how to organize your Python script files, starting with the commands that usually go at the very top of a Python script, which are the import statements.
00:11
Now there are different kinds of import statements in Python. We can import modules from the standard library, which comes pre-packaged with Python. For example, the random module that lets us generate random numbers.
00:23
It could be third-party libraries we’re importing that we’ve installed from elsewhere with something like pip. So it could be modules such as rich, which we will use in our quote generator to make the text look a little bit nicer.
00:36
Or it could be local modules such as another .py file you’ve written, and you’d like to import some functionality from that file into your main script.
00:47 And actually, Python already has a recommendation on how to organize these import statements. First of all, they should be the first thing at the top of your Python file, or potentially after a shebang, as we saw in the previous lesson.
01:01 But Python has these guidelines called PEP 8, which give you stylistic recommendations that if everybody follows, then all our code is much more consistent with each other’s. So Python’s PEP 8 guidelines recommend that import statements go in this order.
01:16 First, the standard library imports, then imports from third parties, and finally, any local imports. And specifically, PEP 8 also says you should leave a blank line in between each of these groups of imports.
01:30
So let’s take a look at this in our quote generator file. So after the shebang, we are starting with importing the random module, which is from the standard library.
01:42
Then we go to a separate group, separated by a blank line. This group is the third-party imports. So we are importing from a third-party library called rich.
01:53
Then we leave another blank line. And then finally, the next group is where you put imports from local files. So we have a separate file called quote_utils.py in the same folder.
02:06
And from there, we are just importing a get_quotes() function, which we will talk about a little bit in another lesson. Now it’s good to try and remember these PEP 8 guidelines and follow them.
02:18 But in order to make our lives a little bit easier, we can use something called a formatter, which will help us automatically organize import statements in the right place. And that’s what the next lesson is all about.
Become a Member to join the conversation.
