Duplication vs. Coupling: When do you actually refactor duplicate code in Python?
When building and maintaining larger Python codebases, one of the classic debates between senior engineers is balancing the DRY (Don't Repeat Yourself) principle against premature coupling.
Consider a situation where two or three separate modules have identical 10-line boilerplate (for example, database connection lifecycle handling, recurring input validation checks, or retry logic):
python # Seen across module_a.py and module_b.py: managed: bool = conn is None if managed: conn = init_db(DB_PATH) try: yield conn finally: if managed: conn.close()