Reliable Script Execution Prevents Import Nightmares
Run scripts as modules with python -m package.module instead of python app.py to treat execution as a proper package, fixing relative import errors like ImportError: attempted relative import with no known parent package. For a project structure like project/app/main.py and utils.py, use python -m app.main from the project root. Always wrap runnable code in def main(): and if __name__ == "__main__": main() to avoid accidental execution during imports, preventing unwanted API calls or DB writes. For development, install watchdog via pip install watchdog and run watchmedo auto-restart -- python app.py to auto-reload on file saves, mimicking hot reload without frameworks.
Transform Debugging with Rich Output and IPython
Replace standard print with from rich import print after pip install rich for automatic colorful, formatted output—e.g., print({"name": "Alex", "role": "Engineer"}) renders beautifully. Add from rich.traceback import install; install() for readable tracebacks that cut cognitive load. Switch your REPL to IPython (pip install ipython; ipython) for autocomplete, syntax highlighting, history, magic commands like %timeit my_function() for benchmarking, and variable? for instant docs, speeding experimentation and decisions.
Cut Boilerplate and Boost Readability with Idioms
Ditch os.path for pathlib: from pathlib import Path; path = Path("folder") / "file.txt", then use path.exists(), path.read_text(), path.write_text("hello") for object-oriented file handling that's scalable. For data classes, use @dataclass from dataclasses instead of manual __init__: @dataclass class User: name: str; age: int auto-generates __init__, __repr__, __eq__, ideal for APIs, AI pipelines, configs, ETL. Swap manual counters i=0; i+=1 with for i, item in enumerate(items):, and prefer simple list comprehensions like results = [num * 2 for num in numbers] over loops for efficiency, but avoid nested conditions that harm readability.
Benchmark Accurately to Optimize Real Performance
Measure execution with from time import perf_counter; start = perf_counter(); ...; print(end - start) instead of time.time(), which lacks precision for APIs, AI pipelines, scraping, or data scripts—critical when slowdowns repeat 400,000 times in production. These hacks reduce mental noise across large codebases, turning friction into flow for sustained productivity.