A library is a file of code that can be used or re-used across programs.
Modules
Modules in Python are libraries that typically have a few functions or features built into it. Their purpose is to encourage re-usability.
Generally the idea is that if we are re-using or “copying and pasting” code from previous projects we can instead re-use our functions functions and import them into a module.
Importing modules
To import a module into a Python program we have to use the import keyword:
import random
coin = random.choice(["heads", "tails"])We can also use from to import specific functions:
from random import choice
coin = choice(["heads", "tails"])Doing it this way will import the choice function into the current namespace of the program (or into the scope of the program, in other words). However, this creates the risk of creating namespace collisions if we have more than one choice function - this can be avoided by importing the entire module and specifying random.choice every time.
Packages
If we have code in a separate folder we must include an empty file named __init__.py to let Python know that the entire folder is a package.