In real projects, you rarely write everything in a single file. You’ll organize code into modules, reuse the rich Standard Library, install third-party packages, read environment variables for configuration, and build simple CLI tools so your scripts are easy to run and test. This lesson shows you how—using short, practical examples you can try right away.
1) Imports & Your Own Modules
Use import to bring code from other files or libraries into your script. You can import from:
- Standard Library (built into Python)
- Third-party packages (installed via
pip) - Your own modules (
.pyfiles in your project)
a) Import styles (quick reference)
import math # import whole module
import math as m # module alias (shorten name)
from math import sqrt # import a single name into local namespace
from math import sqrt as rt # import a single name with alias
print(math.pi, m.e, rt(16))
from module import *) to keep your namespace clean and autocomplete helpful.b) Creating and importing your own module
my_utils.py:
# my_utils.py
def title_case(s: str) -> str:
return " ".join(w.capitalize() for w in s.split())
main.py:
import my_utils
print(my_utils.title_case("hello from python")) # Hello From Python
c) Module search path & script entry point
import sys
print(sys.path) # list of directories Python searches for imports
if __name__ == "__main__":
print("Running as a script") # only runs when file is executed directly
2) Built-in Modules You’ll Use a Lot
Python’s Standard Library is “batteries included.” Below are practical snippets you’ll actually use—followed by brief mentions of other helpful modules.
a) Files & Paths: pathlib (+ os)
from pathlib import Path
data_dir = Path("data")
p = data_dir / "users.csv"
print("Exists?", p.exists())
if p.is_file():
print("Size (bytes):", p.stat().st_size)
else:
data_dir.mkdir(exist_ok=True)
p.write_text("name,city\nAli,Lahore\nAmmar,Karachi\n", encoding="utf-8")
print("Seeded:", p)
b) JSON: json
import json, pathlib
config_path = pathlib.Path("settings.json")
if not config_path.exists():
config_path.write_text(json.dumps({"api_url": "https://api.example.com", "debug": true}), encoding="utf-8")
settings = json.loads(config_path.read_text(encoding="utf-8"))
print("API:", settings["api_url"], "| DEBUG:", settings["debug"])
c) CSV: csv
import csv
with open("data/users.csv", newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
cities = [r["city"] for r in rows]
print("Cities:", cities)
d) Dates & Times: datetime
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
print("UTC now:", now.isoformat())
print("Pretty:", now.strftime("%Y-%m-%d %H:%M UTC"))
e) Counting & Iteration Helpers: collections, itertools
from collections import Counter
from itertools import islice
cities = ["Lahore", "Karachi", "Lahore", "Quetta", "Lahore"]
print("Top cities:", Counter(cities).most_common(2)) # [('Lahore', 3), ('Karachi', 1)]
# islice: get first N items from any iterable
first_two = list(islice(cities, 2))
print(first_two)
f) Randomness & Simple Stats: random, statistics
import random, statistics as stats
nums = [random.randint(1, 10) for _ in range(5)]
print("nums:", nums, "| mean:", round(stats.mean(nums), 2))
Other handy modules (1-line tour)
math: sqrt, floor/ceil, trig, constantstime: sleep, epoch timestampsfunctools: lru_cache, partial, reduceshutil: copy/move/remove directories/filesre: regular expressions for pattern matchingsubprocess: run external commandstyping: type hints for better tooling
3) Third-Party Packages (via pip)
Install once, then import like any other module. Use a virtual environment (python -m venv .venv) to isolate dependencies. Later, in Packaging & Distribution, we’ll learn how to set up and manage virtual environments to keep projects organized.
# install popular data tools
pip install numpy
pip install pandas
# list installed packages
pip list
Quick demo:
import numpy as np
import pandas as pd
arr = np.array([1, 2, 3, 4, 5])
print("Mean:", arr.mean())
df = pd.DataFrame({"city": ["Lahore", "Karachi", "Lahore"], "sales": [120, 200, 180]})
print(df.groupby("city")["sales"].mean())
4) Command-Line Interfaces (CLI) with argparse
Let’s make a small, practical CLI: read a text file and print lines that contain a keyword. Supports a case-insensitive flag and a limit.
# file: grep_like.py
import argparse, sys
def parse_args():
p = argparse.ArgumentParser(description="Filter lines in a file by keyword.")
p.add_argument("filepath", help="Path to the input text file")
p.add_argument("keyword", help="Word to search for")
p.add_argument("-i", "--ignore-case", action="store_true", help="Case-insensitive match")
p.add_argument("-n", "--limit", type=int, default=0, help="Max number of matches to print (0 = no limit)")
return p.parse_args()
def main():
args = parse_args()
try:
with open(args.filepath, encoding="utf-8") as f:
matches = 0
for line in f:
hay = line if not args.ignore_case else line.lower()
needle = args.keyword if not args.ignore_case else args.keyword.lower()
if needle in hay:
print(line.rstrip())
matches += 1
if args.limit and matches >= args.limit:
break
except FileNotFoundError:
print("File not found:", args.filepath, file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
Try it:
python grep_like.py data/users.csv Lahore
python grep_like.py data/users.csv lahore --ignore-case --limit 1
python grep_like.py --help
Tips:
- Write clear
help=text; users will see it in-h/--help. - Use
type=andchoices=for safer parsing. - Exit with a non-zero code on failure (
sys.exit(1)) so scripts can detect errors.
5) Environment Variables (Config outside your code)
Keep secrets and environment-specific settings out of source code. Use os.getenv with sensible defaults; combine with argparse for flexible overrides.
# config_demo.py
import os, argparse
API_URL = os.getenv("API_URL", "https://api.example.com")
DEBUG = os.getenv("DEBUG", "0") == "1" # simple boolean flag
TIMEOUT = int(os.getenv("TIMEOUT", "30")) # cast to int
parser = argparse.ArgumentParser(description="Demo config from env + CLI")
parser.add_argument("--timeout", type=int, default=TIMEOUT, help="Override timeout (seconds)")
args = parser.parse_args()
print("API_URL:", API_URL)
print("DEBUG:", DEBUG)
print("TIMEOUT:", args.timeout)
Try it:
# on Linux/macOS
export API_URL="https://api.example.dev"
export DEBUG=1
python config_demo.py --timeout 10
# on Windows (PowerShell)
$env:API_URL="https://api.example.dev"
$env:DEBUG="1"
python config_demo.py --timeout 10
Key Takeaways
- Organize code using modules; import cleanly with explicit names.
- Standard Library covers most routine tasks: files (
pathlib), data (json,csv), dates (datetime), counting/iteration (collections,itertools), randomness/stats (random,statistics). - Install third-party packages via
pip; use a virtual environment to isolate dependencies. - Build friendly CLIs with
argparse; show helpful--helpand validate inputs. - Read config from environment variables; combine with CLI flags for flexible defaults.
Continue with Debugging, Testing & Best Practices to write clean, reliable, and maintainable Python.
(Optional) Structural Pattern Matching — match/case (Python 3.10+)
Cleaner branching than long if/elif chains by matching shapes and values.
status = 404
match status:
case 200:
print("OK")
case 404:
print("Not Found")
case _:
print("Other")
event = {"type": "click", "x": 120, "y": 40}
match event:
case {"type": "click", "x": x, "y": y} if x >= 0 and y >= 0:
print(f"Click at {x},{y}")
case {"type": "keydown", "key": key}:
print(f"Key: {key}")
case _:
print("Unknown")
(Optional) Date & Time Quick Starter
from datetime import datetime, timezone
from zoneinfo import ZoneInfo # Python 3.9+
now_utc = datetime.now(timezone.utc)
now_pk = now_utc.astimezone(ZoneInfo("Asia/Karachi"))
print(now_utc.isoformat())
print(now_pk.strftime("%Y-%m-%d %H:%M"))
Leave a comment
Your email address will not be published. Required fields are marked *
