During development you might find that you need to include a different code file into your code. This could be another program that you have written or part of Python standard library that does the code feature that you require. Why re-invent the wheel?
A module is a python code file ending in a .py extension. The files that you have created so far in this course have been modules.
A package is a folder containing a module.
To include additional code in this manner you use either the import keyword for the whole package, or from…import for individual modules from a package. This should always be done at the top of your code.
If you look back at the last exercise we had the following at the top of our code:
from random import randint
This effectively said “Go get the randint module from the random package because I want to use it in this program”.
The import code will first look through the Python standard library for a match and then if that fails, checks all the directories listed within the environment’s path starting with the current code directory. Import can be used to find either modules or packages.
You can also limit the import to only include a certain module from a package. If you know that you only need certain functions from a package then you should only include those because this will improve performance by not including code that is never used.
There are coding conventions for the import lines too. They should be split up depending on if they are part of the Python library, a third party package or your own local code. Each of these sections should have a space between them and within each section the imports should be done alphabetically.
from random import randint
import turtle
import thirdpartymodule
import localfile
import secondlocalfile