{"dataset":{"id":"00000000-0000-0000-0000-000000000013","slug":"python-best-practices","name":"Python best practices","description":"Source-linked guidance on Python 3 fundamentals: virtual environments, type hints, pathlib, context managers, and exception handling. Scoped to Python 3; not a general-purpose language reference.","visibility":"public","version":1,"documentCount":5,"publisher":"Koskamo editorial","license":"Original summaries; linked sources retain their own terms.","reviewedAt":"2026-10-04T00:00:00.000Z","readOnly":true,"createdAt":"2026-10-04T00:00:00.000Z","updatedAt":"2026-10-04T00:00:00.000Z"},"total":5,"documents":[{"title":"Handling errors and exceptions","sourceUrl":"https://docs.python.org/3/tutorial/errors.html","text":"Python distinguishes syntax errors, which the parser flags with arrows pointing at the place where the error was detected, from exceptions, errors detected during execution that are not unconditionally fatal. Handle selected exceptions with try and except: the try clause executes first; if no exception occurs the except clause is skipped, and if one occurs the rest of the try clause is skipped and the except clause runs only when the exception's type matches the one named — otherwise the exception propagates to outer try statements, and with no handler it becomes an unhandled exception that stops execution with an error message. A try statement may have several except clauses, but at most one handler executes, and handlers only see exceptions raised in their own try clause. One clause may name several exceptions, as in except (RuntimeError, TypeError, NameError), and a clause matches instances of the named class or its derived classes, so the first matching clause is triggered; ordering handlers from derived to base classes is Koskamo editorial guidance drawn from that rule. Scope: Python 3. Reviewed October 4, 2026.","id":"python-best-practices:Handling errors and exceptions","version":1,"createdAt":"2026-10-04T00:00:00.000Z","updatedAt":"2026-10-04T00:00:00.000Z"},{"title":"Context managers and the with statement","sourceUrl":"https://docs.python.org/3/reference/compound_stmts.html#the-with-statement","text":"The with statement wraps the execution of a block with methods defined by a context manager, encapsulating common try…except…finally usage patterns for convenient reuse. The context expression is evaluated to obtain a context manager, whose __enter__() and __exit__() methods are loaded; __enter__() is invoked, and if an as target was included its return value is assigned to it. The language reference guarantees that if __enter__() returns without an error, __exit__() will always be called. After the suite runs, __exit__() is invoked: if an exception caused the suite to exit, its type, value, and traceback are passed as arguments, otherwise three None arguments are supplied. When the suite exits due to an exception, a false return from __exit__() reraises the exception and a true return suppresses it; for exits not caused by an exception the return value is ignored. A single with statement may carry several comma-separated items. Scope: Python 3. Reviewed October 4, 2026.","id":"python-best-practices:Context managers and the with statement","version":1,"createdAt":"2026-10-04T00:00:00.000Z","updatedAt":"2026-10-04T00:00:00.000Z"},{"title":"Object-oriented filesystem paths with pathlib","sourceUrl":"https://docs.python.org/3/library/pathlib.html","text":"The pathlib module, added in Python 3.4, offers classes representing filesystem paths with semantics appropriate to different operating systems. Path classes divide into pure paths, which provide purely computational operations without I/O, and concrete paths, which inherit from pure paths and add I/O. Path is most likely what you need: it instantiates a concrete path for the platform the code runs on. Use a pure class such as PureWindowsPath when manipulating Windows paths on a Unix machine (a WindowsPath cannot be instantiated there) or when code must manipulate paths without accessing the OS. Join segments with the / operator — Path('/etc') / 'init.d' / 'reboot' — list subdirectories with iterdir(), search a tree with glob('**/*.py'), query with exists() and is_dir(), and open files with open(). The resolve() method makes the path absolute, resolving any symlinks. For low-level path manipulation on strings, use the os.path module. Scope: Python 3. Reviewed October 4, 2026.","id":"python-best-practices:Object-oriented filesystem paths with pathlib","version":1,"createdAt":"2026-10-04T00:00:00.000Z","updatedAt":"2026-10-04T00:00:00.000Z"},{"title":"Type hints and the typing module","sourceUrl":"https://docs.python.org/3/library/typing.html","text":"The typing module, added in Python 3.5, provides runtime support for type hints, but the Python runtime does not enforce function and variable annotations — they are consumed by third-party tools such as type checkers, IDEs, and linters. Hints can be simple classes like float or str, or the typing module's vocabulary of more advanced hints; the typing_extensions package backports new features to older versions of Python. A hint such as edge_length: float marks the expected argument type and -> str the return type. Type aliases simplify complex signatures: type Vector = list[float] creates a TypeAliasType instance that static checkers treat as equivalent to list[float]; the type statement is new in Python 3.12, and for backwards compatibility aliases can also be created through simple assignment. The typing system is standardised via PEPs, so reference material broadly applies to most type checkers. Scope: Python 3. Reviewed October 4, 2026.","id":"python-best-practices:Type hints and the typing module","version":1,"createdAt":"2026-10-04T00:00:00.000Z","updatedAt":"2026-10-04T00:00:00.000Z"},{"title":"Virtual environments with venv","sourceUrl":"https://docs.python.org/3/tutorial/venv.html","text":"Python applications often need specific library versions that conflict with one another, and a virtual environment solves this: a self-contained directory tree containing a Python installation for a particular version plus additional packages. The venv module creates and manages virtual environments and installs the Python version from which the command was run. Run python -m venv with a directory path to create one; .venv is a common location, hidden in the shell and not clashing with .env environment-variable files. Activate with Scripts\\activate on Windows or source bin/activate on Unix or macOS (activate.csh and activate.fish exist for the csh and fish shells); activation changes the shell prompt and makes python resolve to that installation, but does not alter PYTHONPATH, and the tutorial's best practice is to unset it. Manage packages with pip (install, uninstall, freeze), pin a version with ==, and leave the environment with deactivate. Scope: Python 3. Reviewed October 4, 2026.","id":"python-best-practices:Virtual environments with venv","version":1,"createdAt":"2026-10-04T00:00:00.000Z","updatedAt":"2026-10-04T00:00:00.000Z"}]}