Pythonadvanced 9 min
Import code from the standard library and from your own files, and organise projects.
How to import modules, use the standard library, split your own code into files and understand packages and __name__.
Python's strength is its huge amount of ready-made code. Modules let you use it, and also let you keep your own project organised in files that each do one job.
A module is simply a .py file. You load it with import:
Variations:
from math import sqrt, pi: import specific names.import datetime as dt: give a module a shorter name.The standard library comes with Python, so there is nothing to install: math, random, json, datetime, os, pathlib, collections and many more.
Your own module works the same way. If you save helpers.py next to your main file, then import helpers works.
A package is a folder of modules (with an __init__.py file). Third-party packages are installed with pip.
if __name__ == "__main__": runs code only when the file is run directly, not when it is imported. Use it for demo code at the bottom of a module.
math.sqrt(16) is 4.0 and round(math.pi, 4) is 3.1416.json.dumps turns a dictionary into JSON text; json.loads turns it back. The first score is 90.date(2025, 3, 14).strftime("%d %b %Y") formats the date: 14 Mar 2025.helpers.py to the file system and then imports it. Because the file is brand new, we add the current folder to sys.path and refresh Python's import cache first. helpers.shout("hello") prints HELLO!.__name__ is "__main__", which is why the guard works.Use the random module to pick a random item from a list. (The result changes each run.)
random.py, which then hides the real one.from module import *, which pollutes your names. Import what you need.__name__.import brings in modules; the standard library is built in..py files are modules; folders with __init__.py are packages.if __name__ == "__main__":.Next: keeping each project's packages separate.
import math
print(math.sqrt(16))import math
import json
from datetime import date
print(math.sqrt(16), round(math.pi, 4))
data = {"name": "Asha", "scores": [90, 85]}
text = json.dumps(data)
print(text)
print(json.loads(text)["scores"][0])
print(date(2025, 3, 14).strftime("%d %b %Y"))
# Write our own module to a file, then import it
with open("helpers.py", "w") as f:
f.write("def shout(text):\n return text.upper() + '!'\n")
import sys, importlib
sys.path.append(".") # make sure the current folder is searched
importlib.invalidate_caches() # notice the file we just created
import helpers
print(helpers.shout("hello"))
print(__name__)