intermediatePython Framework • Core Concepts

Modules & Packages

Join 1.2k+ learners

What is a Module?

A module is simply a Python file ending in `.py`. You can define functions, classes, and variables in a module and `import` them into other files to reuse code.

Python
# math_utils.py def add(a, b): return a + b # main.py import math_utils print(math_utils.add(5, 3))

Import Styles

You can import an entire module, specific items, or give them aliases. Choose the style that makes your code most readable.

Python
import math from math import sqrt import numpy as np print(math.pi) print(sqrt(16)) # print(np.array([1, 2]))

Packages & __init__.py

A package is a directory containing multiple module files. It must (usually) contain a special file named `__init__.py`, which can be empty or used to expose specific functions.

Python
my_project/ ├── main.py └── graphics/ ├── __init__.py ├── shapes.py └── colors.py # main.py from graphics import shapes

Virtual Environments

A virtual environment is a self-contained directory that contains a Python installation for a specific project. This prevents version conflicts between different projects.

Python
# Terminal commands python -m venv venv # Create source venv/bin/activate # Activate (Mac/Linux) .\venv\Scripts\activate # Activate (Windows) pip install requests # Install packages safely

Master this concept

Hands-on practice is the fastest way to learn. Head over to our interactive workspace to solve this topic's challenge.

Launch Editor

Visual Lab

Project Structure

main.py
import utils
utils.py
from pkg import ...
my_package/
Start/End
Condition
Action

New Challenge available!

Master Modules & Packages with a hands-on task.