Modules
import, writing your own module, packages and pip.
All lessons · Python lessons: learn from scratch
Importing ready-made modules
A module is simply a file of Python code. With import you use functions someone else wrote. There are three forms: the whole module, a part of it, or with a new name.
import math from random import randint import statistics as st print(math.sqrt(81)) # 9.0 print(randint(1, 6)) # random 1..6 print(st.mean([4, 8, 9])) # 7.0
Writing from module import * is discouraged: names get mixed up and you cannot tell where something came from.
Writing your own module
Every .py file is a module. Write temp.py, define a function in it, and import it from another file. Being in the same folder is enough.
# temp.py
def c_to_f(c):
return c * 9 / 5 + 32
if __name__ == "__main__":
print(c_to_f(100)) # runs only when executed directly
# main.py
import temp
print(temp.c_to_f(37))The if __name__ == "__main__": block runs when the module is executed directly but not when it is imported. This lets one file be both a program and a library.
Packages and pip
A package is a folder containing modules (older versions needed an __init__.py file). Third-party packages that do not ship with Python are installed with pip. For projects it is wise to create a separate virtual environment.
python -m venv .venv # Windows: .venv\Scripts\activate # macOS/Linux: source .venv/bin/activate pip install requests pip list