P01.5 · Modules, packages and environments
P01.5 L0 · Foundation 4 lessons · about 100 min Live · in review
Part of P01 Python from Zero in the Programming and Data track.
Every later course begins with a few import lines, so this module takes them apart. A module is a file of Python code with names of its own; import finds it, runs it once and binds one name to it. These four lessons use the standard library beside the code you wrote by hand, turn your own functions into a module and a package, follow Python’s search for a module folder by folder, install packages such as NumPy with pip, pin their versions, and give each project a virtual environment of its own, so that a result can be repeated on another machine.
What you need first. Values, comparisons and the tolerance test of P01.2, loops over a list written in square brackets (P01.3), and functions with their global and local names (P01.4). No list methods, string methods or files are needed; terminal commands are explained as they appear.
Lessons
Modules and import P01.5.1 25 min
A module is a file of Python code with names of its own. See the three things import does, the three forms of import and the one name that each binds, and the standard library’s math, statistics and random set beside the versions you wrote by hand.
Writing your own module and package P01.5.2 25 min
Move mean and predict into a file of your own and import it from a script beside it. Follow Python’s search through the folders of sys.path, write a file that is both a script and a module, make a package, and avoid the trap of a file called random.py.
Installing packages with pip P01.5.3 25 min
Code written by others arrives as packages from the Python Package Index. Install, list and inspect them with python -m pip, see where they land, compare version numbers one whole number at a time, pin them with ==, and import NumPy as np for the first time.
Virtual environments P01.5.4 25 min
Two projects that pin different versions of one package cannot share one installation. Give each its own virtual environment with python -m venv, activate it on Windows, macOS or Linux, check which Python is running, and rebuild it from requirements.txt so that others can repeat your results.
The interactive
P01.5-X1 · Import resolver. Choose an import and which of two environments is active, then step Python’s search down the column of folders it tries: the project folder, the standard library and the environment’s site-packages. Watch it stop at the first match, report the version it found, or run out of folders with ModuleNotFoundError; a switch puts a file named random.py in the project folder. It lives in Virtual environments.