Python 101Free
MODULES AND FILES

Modules and Imports

Break code into multiple files and reuse what others have written.

SECTION 01

What is a module

A module is a Python file. When you import it, Python runs the file once and exposes its top-level names through a namespace you can refer to by the module's name.

This is the basic mechanism for splitting code across files. Define utility functions in math_utils.py, write import math_utils from another file, and call math_utils.add(2, 3). The names from the imported file are reachable through the module name without polluting the caller's namespace.

A folder containing an __init__.py file is a package, which is a module that contains other modules. The mechanics are the same; packages just give you a tree.

SECTION 02

Import forms

There are three common import forms. import json brings in the whole module, callers write json.loads(...). from json import loads pulls just loads into the local namespace, callers write loads(...) directly. import numpy as np is a renamed import, useful when the module name is long or clashes with something else.

Each form has a tradeoff. The import x form is the most explicit about where a name came from. The from x import y form is shorter at the call site but loses that signal. The as form is great for canonical aliases (np, pd, tf) and noisy elsewhere.

In most code, default to import x unless the module name is awkward at every call site or the imported name is genuinely well-known.

python
import json
data = json.loads(text)

from json import loads
data = loads(text)

import numpy as np
arr = np.array([1, 2, 3])
SECTION 03

Standard library tour

Python ships with a large standard library. Five modules cover most beginner tasks: os for environment variables and basic file system queries, json for serializing to and from JSON text, datetime for dates and times, math for numeric helpers, random for randomness.

Before reaching for pip install, check whether the standard library already has what you need. The stdlib is well-tested, dependency-free, and available on every Python install. Third-party packages are great when you genuinely need them and overhead when you do not.

The official Python docs list every stdlib module with examples. Bookmarking the index is one of the better moves a beginner can make.

python
import os, json, datetime, math, random

os.environ.get("HOME")
json.dumps({"a": 1})              # '{"a": 1}'
datetime.datetime.now()
math.sqrt(2)                      # 1.4142...
random.randint(1, 6)              # 1..6 inclusive
NEXT →
File I/O