Python Basics
Python is useful for scripts, data handling and small services. Keep the interpreter, dependencies and project files organised from the start.
Environments
Use the Python version required by the project. A virtual environment gives the project its own installed packages. Keep it out of Git and recreate it from recorded dependencies rather than copying its directory between machines.
Use python -m pip with the intended interpreter. A package installed for another interpreter will not necessarily be visible to the one running your code. See the virtual environment documentation.
Data structures
| Structure | Use |
|---|---|
| List | Ordered, mutable sequence |
| Tuple | Fixed sequence of references |
| Dictionary | Mapping from hashable keys to values |
| Set | Membership and distinct hashable values |
Assignment binds a name to an object; it does not copy the object. A shallow copy duplicates the outer container while retaining references to its elements. A tuple can contain a mutable object even though the tuple's own entries cannot be reassigned.
Functions and iteration
Keep functions focused on one operation. Pass dependencies explicitly when that makes behaviour easier to follow. Type hints describe intended types but do not enforce them automatically at runtime.
Default argument expressions are evaluated when the function is defined. A mutable default can therefore retain changes between calls. Use a fresh object inside the function when each call needs its own state.
An iterator produces values as requested. A generator can avoid building a whole result in memory, but it is generally consumed as it is read. Consider who owns an iterator before passing it to several consumers.
Files and failures
Use a context manager for files and other resources requiring cleanup. Choose the encoding explicitly when reading text from a defined format. Catch exceptions where you can recover or give the caller useful context.
Separate parsing, computation and output so each part can be checked independently. Read a traceback from the failing operation through its callers rather than changing the first line that looks unfamiliar.