📖 How Python's Documentation Is Organized
The official Python documentation is not one single tutorial. It is a documentation set containing a beginner-friendly Tutorial, a precise Language Reference, the Standard Library reference, setup/usage guides, HOWTOs, packaging guidance, C/API material, FAQs, deprecations, indexes and a glossary. The current official docs available at the time these notes were enhanced are for Python 3.14.6.
🎓 Tutorial
Learn the language progressively and informally. Best for first learning and guided practice.
⚖️ Language Reference
Precise syntax and core semantics: lexical analysis, data model, expressions, statements, execution model, imports and grammar.
📦 Library Reference
Built-in functions, built-in types, exceptions and the standard library modules.
🛠️ HOWTOs
Deep practical guides for focused topics such as logging, descriptors, regular expressions, sockets and more.
🧠 Language Reference Checklist
Lexical analysisLine structure, indentation, identifiers, keywords, literals, strings, bytes, numbers, operators and delimiters.
Data modelObjects, values, types, mutability, special methods, coroutines and object identity.
Execution modelProgram structure, namespaces, scopes, name binding, exceptions and runtime components.
Import systemModules, packages, importlib, search paths, loaders, finders and relative imports.
ExpressionsCalls, attribute access, subscriptions, slicing, await, arithmetic, bitwise operations, comparisons, boolean operations, assignment expressions, lambdas and precedence.
StatementsAssignment, assert, pass, del, return, yield, raise, break, continue, import, global, nonlocal and type statements.
Compound statementsif, while, for, try, with, match, function definitions, class definitions and coroutines.
GrammarThe formal grammar provides the syntax foundation for the language.
🧰 Built-in Functions Reference Map
| Area | Functions to master | Typical use |
| Input/output | print(), input(), open() | Console and file I/O |
| Conversion | bool(), int(), float(), complex(), str(), bytes(), bytearray() | Convert values |
| Collections | list(), tuple(), set(), frozenset(), dict() | Create containers |
| Iteration | iter(), next(), enumerate(), zip(), reversed(), range() | Build iteration pipelines |
| Inspection | type(), isinstance(), issubclass(), dir(), vars(), id(), callable() | Understand objects |
| Aggregation | len(), sum(), min(), max(), all(), any() | Compute collection properties |
| Functional | map(), filter(), sorted(), abs(), round() | Transform and order data |
| Execution | eval(), exec(), compile() | Dynamic execution; use with extreme caution |
| Attributes | getattr(), setattr(), hasattr(), delattr() | Dynamic object access |
📦 Standard Library — What You Should Know
| Module / Package | Purpose | Learn these first |
| pathlib | Filesystem paths | Path, exists, glob, read_text, write_text |
| os / shutil | OS and file operations | environ, walk, copy, move, rmtree |
| sys | Interpreter/runtime information | argv, path, exit, version, stdin/stdout/stderr |
| json | JSON serialization | load, loads, dump, dumps |
| csv | CSV data | reader, writer, DictReader, DictWriter |
| sqlite3 | Embedded SQL database | connect, cursor, execute, commit |
| datetime | Dates and times | date, datetime, timedelta, timezone |
| re | Regular expressions | compile, search, match, findall, sub |
| math / statistics | Numerical utilities | sqrt, ceil, floor, mean, median |
| random | Pseudorandom generation | randint, choice, shuffle, sample |
| collections | Specialized containers | Counter, defaultdict, deque, namedtuple |
| itertools | Iterator building blocks | chain, product, permutations, combinations |
| functools | Functional helpers | reduce, partial, wraps, lru_cache |
| contextlib | Context manager helpers | contextmanager, suppress, ExitStack |
| dataclasses | Data-focused classes | dataclass, field, asdict |
| typing | Static type annotations | TypeVar, Generic, Protocol, TypedDict, Literal |
| logging | Application logging | Logger, levels, handlers, formatters |
| argparse | CLI argument parsing | ArgumentParser, add_argument |
| subprocess | Run external programs | run, Popen, CompletedProcess |
| threading / multiprocessing | Concurrency | Thread, Lock, Process, Queue |
| asyncio | Asynchronous I/O | async, await, Task, gather |
| unittest | Testing | TestCase, assert methods, mock |
🔤 Complete Built-in Type Study Map
- Numeric: int, float, complex, bool.
- Sequences: list, tuple, range, str.
- Binary: bytes, bytearray, memoryview.
- Mappings: dict.
- Sets: set, frozenset.
- Iteration: iterator and generator protocols.
- Callables: functions, methods, classes and callable instances.
- Context managers: objects implementing __enter__ and __exit__.
- Exceptions: BaseException hierarchy and custom exception classes.
🔁 Iterators & Generators
An iterable can produce an iterator. An iterator implements the iterator protocol, especially __iter__() and __next__(). Generators provide a convenient way to create iterators with yield.
def countdown(n):
while n:
yield n
n -= 1
for value in countdown(3):
print(value)
Use generators for streaming data and memory-efficient pipelines. Remember that a generator is consumed as you iterate over it.
🎯 Decorators
from functools import wraps
def log_call(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("Calling", func.__name__)
return func(*args, **kwargs)
return wrapper
@log_call
def add(a, b):
return a + b
Decorators receive a callable and return a callable. functools.wraps preserves useful metadata such as __name__ and __doc__.
🧩 Context Managers
with open("data.txt", encoding="utf-8") as file:
text = file.read()
The with statement delegates setup and cleanup to a context manager. It is central to safe file handling, locks, database connections and resource management.
🧪 Testing Documentation
import unittest
def add(a, b):
return a + b
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
if __name__ == "__main__":
unittest.main()
Test normal cases, boundary cases and failure cases. Keep tests deterministic and isolate external resources where practical.
📝 Type Hints
from typing import Iterable
def total(values: Iterable[float]) -> float:
return sum(values)
Annotations document intended interfaces and enable static analysis. Python remains dynamically typed at runtime; annotations do not automatically enforce types.
📊 Dataclasses
from dataclasses import dataclass
@dataclass
class Student:
name: str
age: int
student = Student("Hamza", 20)
print(student)
Dataclasses reduce boilerplate for data-centric classes by generating methods such as __init__ and __repr__, with configurable equality and ordering behavior.
⚡ Async Programming
import asyncio
async def job(name):
await asyncio.sleep(1)
return name
async def main():
results = await asyncio.gather(job("A"), job("B"))
print(results)
asyncio.run(main())
asyncio is designed for concurrent I/O-bound work. async defines a coroutine function; await suspends it while another task can make progress.
🧵 Threads vs Processes vs Async
| Tool | Best fit | Key idea |
|---|
| asyncio | Many I/O tasks | Cooperative concurrency |
| threading | I/O and blocking libraries | Multiple threads in one process |
| multiprocessing | CPU-heavy Python work | Separate processes |
Choose based on workload and library behavior, not because one model is universally faster.
📦 Packaging & Virtual Environments
python -m venv .venv
# Windows PowerShell
.venv\Scripts\Activate.ps1
# install dependencies
python -m pip install requests
# export a simple dependency list
python -m pip freeze > requirements.txt
For modern projects, learn pyproject.toml, build backends, package metadata, wheels, source distributions, dependency specifications and publishing workflows. Keep development environments isolated.
🖥️ Command-Line Applications
import argparse
parser = argparse.ArgumentParser(description="Demo CLI")
parser.add_argument("name")
args = parser.parse_args()
print(f"Hello {args.name}")
argparse is included in the standard library and is a strong foundation for portable CLI tools.
📋 Logging
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.info("Application started")
logger.warning("Something needs attention")
Prefer logging over print statements for applications that need levels, timestamps, handlers, files or structured operational output.
🔐 Security Rules
- Never execute untrusted input with eval() or exec().
- Do not deserialize untrusted pickle data.
- Validate paths and user-controlled filenames.
- Do not hard-code passwords, tokens or API keys.
- Use HTTPS and secure credential storage for network applications.
- Keep dependencies updated and inspect dependency provenance.
🚀 Performance Checklist
- Measure first with profiling tools.
- Choose appropriate data structures and algorithms.
- Avoid unnecessary repeated work.
- Use generators for streaming pipelines.
- Use caching when repeated computation is expensive.
- Move CPU-heavy work to suitable native/vectorized libraries or processes when appropriate.
- Do not sacrifice readability for tiny speculative optimizations.
📚 Official Documentation Links
⚠️Important: “All documentation” is too large to reproduce verbatim in one HTML file. This workbook therefore adds a broad, structured reference and direct links to the official documentation. The official manuals remain the authoritative source for exact behavior and version-specific details.
🎓 Final Mastery Checklist
☐ SyntaxCan you read and write ordinary Python without looking up basic syntax?
☐ Data structuresCan you choose list, tuple, set or dict based on the problem?
☐ FunctionsCan you design clean reusable functions with sensible interfaces?
☐ ExceptionsCan you distinguish expected failures from programmer bugs?
☐ FilesCan you safely read/write text, JSON, CSV and paths?
☐ OOPCan you use classes without overusing inheritance?
☐ AdvancedCan you explain generators, decorators, context managers and async?
☐ ToolingCan you use venv, pip, tests, logging and a debugger?
☐ ProjectsCan you build a complete CLI or small application from scratch?
☐ DocumentationCan you navigate the Tutorial, Language Reference and Library Reference to solve unfamiliar problems?