Menu

Modules and Packages

Introduction

As your projects grow, you'll want to organize your code into modules (single .py files) and packages (directories of modules). Python's import system makes this straightforward.

Importing modules

# Standard library imports
import os
import sys
from datetime import datetime
from pathlib import Path

# Your own modules
# If you have a file called utils.py:
from utils import helper_function
import utils

# Package structure:
# myproject/
#   __init__.py
#   models/
#     __init__.py
#     user.py
#   utils/
#     __init__.py
#     helpers.py

# Installing third-party packages
# pip install requests
import requests

Virtual environments

# Create a virtual environment
# python3 -m venv venv
# source venv/bin/activate  (Linux/Mac)
# venv\Scripts\activate     (Windows)

# Freeze dependencies
# pip freeze > requirements.txt

# Install from requirements
# pip install -r requirements.txt

Assignment

  1. Create a Python package with at least 2 modules and import functions between them.
  2. Set up a virtual environment and install a third-party package like requests.
  3. Create a requirements.txt for your project.

Support me!

I am a software engineer giving back to the community - my name is Musila Peter. Join me in empowering learners around the globe by supporting SaneGenius!