# This Is Why Your Python Code Turns Into Spaghetti ## Summary Here’s a concise yet comprehensive summary of the video transcript: --- ### **Summary: Using Abstraction to Improve Python Code Design** The video demonstrates how to refactor a Python script that applies image filters (e.g., grayscale, invert) to avoid spaghetti code caused by excessive imports and tight coupling. The original design suffers from: - **Fragility**: Adding new filters requires modifying multiple files. - **Testing difficulty**: Dependencies on concrete implementations make isolation hard. - **Code duplication**: Repeated imports and type checks (e.g., `isinstance`) clutter logic. #### **Solutions via Abstraction** #### 1. **Abstract Base Classes (ABCs)** - Define a `FilterBase` class with required methods (`apply`, `configure`). - Subclasses (e.g., `GrayscaleFilter`, `InvertFilter`) enforce a consistent interface. - **Pros**: Explicit contracts; shared attributes (e.g., `enabled`) can be moved to the base class. - **Cons**: Requires inheritance, which some developers find un-Pythonic. #### 2. **Protocols (Duck Typing)** - Define a `FilterProtocol` specifying expected methods (no inheritance needed). - Filters need only implement the protocol’s methods. - **Pros**: More flexible; aligns with Python’s dynamic typing. - **Cons**: No runtime enforcement; errors surface only when type-checked. #### 3. **Functional Approach** - Replace classes with functions (e.g., `apply_grayscale(image, intensity)`). - Use `Callable` types or `functools.partial` to bind configurations (e.g., pre-setting `intensity`). - **Pros**: Simpler for stateless operations; leverages closures. - **Cons**: Limited metadata (e.g., no `__name__` with `partial`); may confuse teams unfamiliar with functional paradigms. #### **Key Takeaways** - **Abstraction reduces coupling**: Depend on interfaces (e.g., `FilterBase`) rather than concrete implementations. - **Centralize "messy" code**: Confine imports and setup to a single module (e.g., `main.py`). - **Choose the right tool**: - Use **ABCs** for hierarchical contracts. - Use **Protocols** for duck typing. - Use **functions** for simplicity, but beware of limitations. The video concludes by encouraging viewers to adopt abstractions early to keep code scalable and maintainable. --- ### **Tailored for Native English Speakers** The summary avoids jargon where possible, uses active voice, and structures ideas logically—making it accessible while retaining technical precision. Let me know if you'd like any refinements! ## Details - Duration: 21m 9s - URL: [This Is Why Your Python Code Turns Into Spaghetti](https://youtu.be/SNqwNILX1Gg?si=L5GavufFXjKVeCsE) ## Tags - PythonCodeDesign - AbstractionInPython - SpaghettiCode - RefactoringPython - AbstractBaseClasses - DuckTyping - FunctionalProgramming - CodeMaintainability - YouTube - Video - Python,Dev