greet.py1print("greet loaded")2def hello(name):3 print("Hello,", name)sys.modulesmain.py1import greet2greet.hello("Ana")3import greet4from shapes import square5print(square.area(3))import gretshapes/__init__.pysquare.py1def area(side):2 return side * side__name__ == '__main__'__name__ == 'greet'ModuleNotFoundErrorgreetgreet loadedgreetHello, Anagreetshapes.square9
Code cards: main.py (the program you run), greet.py and square.py (modules)Folder tray: the package shapes/ with its __init__.pysys.modules: every module loaded so far, by nameTerminal: what the program printsA module is a .py file; main.py imports the module greet and the module square from the package shapes/. Each step lights the parts it is about. A token hops from a line of main.py to the file it imports, from a module to the terminal or into sys.modules, and from a call to the terminal. The terminal's lines and the sys.modules cells crossfade as modules load. The second import of greet finds it in sys.modules and prints nothing. In the last step line 1 is misspelt as import gret and Python raises ModuleNotFoundError.

Modules

  1. A module is just a file of Python code. greet.py is the module greet: its name is the file name without .py. Other programs can use its code with import instead of copying it.

Packages

Names and errors

Try it yourself

;; step 1/11
# greet.py
print("greet loaded")
def hello(name):
    print("Hello,", name)

# any .py file is a module; its name is the
# file name without .py: greet

sys.path starts with the folder of the script you ran (or the current folder at the >>> prompt), then any folders listed in the PYTHONPATH environment variable, then the standard library and site-packages, where pip installs packages. sys.modules also holds many modules Python loads for itself at start-up (sys, builtins and others); the figure shows only the ones main.py adds.