Fundamentals 13 min read

8 Python Tricks to Save You 30 Minutes Every Day

The article presents eight practical Python techniques—from using python -m to avoid import errors, leveraging rich for better debugging output, pathlib for path handling, dataclasses to reduce boilerplate, enumerate, proper __main__ guard, perf_counter for benchmarking, and watchdog for hot-reloading—each with code examples, showing how they cut down repetitive tasks and improve productivity.

IT Services Circle
IT Services Circle
IT Services Circle
8 Python Tricks to Save You 30 Minutes Every Day

TL;DR

Small frictions like frequent ImportError, manual __init__, and os.path path concatenation slow you down more than algorithmic gaps.

All eight tricks come from the Python standard library or a single pip install; no new frameworks or refactoring needed.

Use python -m to avoid import errors, pathlib instead of os.path, dataclass to cut boilerplate, and rich to beautify debugging—freeing cognitive resources for real problems.

Scenario Definition

After four years of Python development, the author observed that the real speed killers are tiny annoyances that happen dozens of times a day, such as ImportError, noisy debug prints, manual __init__ definitions, and clunky path concatenation.

Core Techniques

Technique 1: Use python -m to Run Scripts and Avoid Import Errors

Typical novice command: python app/main.py When the project grows, this often triggers:

ImportError: attempted relative import with no known parent package

Running the module as a proper package fixes the issue:

python -m app.main
I saw an intern spend two hours debugging this error before fixing the command.

Technique 2: Use rich for Clear Debug Output

Standard print() is functional but hard to read for nested structures. With rich:

from rich import print

data = {"user": "小王", "requests": 142, "errors": [{"code": 503, "msg": "Service Unavailable", "count": 12}, {"code": 429, "msg": "Rate Limited", "count": 7}]}
print(data)

The output is syntax‑highlighted and indented, making complex JSON instantly understandable. Adding a single line:

from rich.traceback import install
install()

turns all tracebacks into colored, layered stacks, reducing cognitive load.

Technique 3: Replace os.path with pathlib

Legacy code:

import os
config_path = os.path.join("project", "config", "app.yaml")
if os.path.exists(config_path):
    content = open(config_path).read()

Modern pathlib version:

from pathlib import Path
config_path = Path("project") / "config" / "app.yaml"
if config_path.exists():
    content = config_path.read_text()
Path

objects provide read_text(), write_text(), read_bytes(), glob(), etc., eliminating the need for open() and manual joins.

Technique 4: Use dataclasses to Eliminate Boilerplate

Instead of writing an explicit __init__, declare a data class:

from dataclasses import dataclass

@dataclass
class LLMConfig:
    model: str = "claude-sonnet-4-6"
    temperature: float = 0.7
    max_tokens: int = 4096

This automatically generates __init__, __repr__, and __eq__, which is especially handy for API configs, ETL pipelines, or any plain‑data holder.

Technique 5: Use enumerate() and List Comprehensions

Old loop:

i = 0
for name in names:
    print(i, name)
    i += 1

Python’s built‑in enumerate does the same in one line:

for i, name in enumerate(names):
    print(i, name)

Similarly, replace multi‑line list building with a comprehension: results = [n * 2 for n in numbers] But avoid overly complex comprehensions; if they become hard to read, revert to a regular loop.

Technique 6: Guard Entry Point with if __name__ == "__main__"

Encapsulating script logic in a main() function and protecting it prevents accidental execution when the file is imported, which could otherwise trigger unwanted API calls, DB writes, or emails.

def main():
    process_data()
    generate_report()

if __name__ == "__main__":
    main()

Technique 7: Use time.perf_counter() for Accurate Benchmarks

Common mistake: using time.time() for performance measurement, which is low‑resolution and affected by system clock changes.

from time import perf_counter
start = perf_counter()
# ... code to benchmark ...
elapsed = perf_counter() - start
print(f"耗时: {elapsed:.4f} 秒")
perf_counter

provides high‑resolution, monotonic timing ideal for micro‑benchmarks.

Technique 8: Use watchdog for Hot Reloading

Typical edit‑run‑repeat cycle can be automated:

pip install watchdog
watchmedo auto-restart --patterns="*.py" -- python your_script.py

Saving a file now automatically restarts the script, turning a manual workflow into an instant feedback loop.

Pitfalls & Reminders

When using python -m, replace slashes with dots (e.g., app/main.pyapp.main) to avoid "No module named" errors.

Avoid mutable default values in dataclasses; use field(default_factory=list) instead of [] or {}.

Keep list comprehensions shallow—no more than two nested levels or complex if clauses. perf_counter() returns seconds but its zero point is arbitrary; use it only for differences.

Full Template + Next Steps

A ready‑to‑copy script combines all tricks:

"""Daily Python script template"""
from pathlib import Path
from time import perf_counter
from dataclasses import dataclass
from rich import print
from rich.traceback import install
install()

@dataclass
class Config:
    data_dir: str = "data"
    output_dir: str = "output"

def process_files(config: Config) -> list[Path]:
    """Read all CSV files under data_dir and return their paths."""
    data_path = Path(config.data_dir)
    if not data_path.exists():
        raise FileNotFoundError(f"目录不存在: {config.data_dir}")
    return list(data_path.glob("*.csv"))

def main():
    start = perf_counter()
    config = Config()
    files = process_files(config)
    for i, f in enumerate(files):
        print(f"[{i}] {f.name}")
    print(f"
[green]处理完成,共 {len(files)} 个文件,耗时 {perf_counter() - start:.3f}s[/green]")

if __name__ == "__main__":
    main()

Future enhancements could include adding rich.progress bars, using watchdog to auto‑trigger processing on file changes, or swapping dataclasses for pydantic.BaseModel for runtime validation.

Conclusion

Each of these eight small tricks removes a source of friction, saves minutes per day, and cumulatively yields a noticeable productivity boost. The real gain is freeing mental bandwidth for higher‑value problems rather than repetitive boilerplate.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

DebuggingPythonproductivityWatchdogpathlibrichdataclassesperf_counter
IT Services Circle
Written by

IT Services Circle

Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.