From eb6f66f637930618e7be94e976885b17421900be Mon Sep 17 00:00:00 2001 From: Diego Colombo Date: Wed, 28 Jan 2026 16:47:12 +0000 Subject: [PATCH] docs: add encapsulation boundary rules (Principle 7) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add principle to PYTHON_BEST_PRACTICES.md about not accessing private attributes from outside a class. Includes table of anti-patterns and code example. Motivated by microsoft/amplifier-app-cli#70. 🤖 Generated with [Amplifier](https://github.com/microsoft/amplifier) Co-Authored-By: Amplifier <240397093+microsoft-amplifier@users.noreply.github.com> --- context/PYTHON_BEST_PRACTICES.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/context/PYTHON_BEST_PRACTICES.md b/context/PYTHON_BEST_PRACTICES.md index 9610d2c..365af88 100644 --- a/context/PYTHON_BEST_PRACTICES.md +++ b/context/PYTHON_BEST_PRACTICES.md @@ -98,6 +98,29 @@ from .config import load_config - Group with blank lines between sections - Combine `from x import a, b` for related items only +### 7. Respect Encapsulation Boundaries + +**Never access private attributes (`_name`) from outside a class.** Private attributes are implementation details that can change without notice. + +| Pattern | Problem | Correct Approach | +|---------|---------|------------------| +| `getattr(obj, "_internal", None)` | Bypasses encapsulation | Request a public API | +| `obj._private_attr` | Depends on implementation | Use protocol/interface | +| Chained unwrapping | Compounds fragility | Expose capability at top level | + +```python +# BAD: Reaching into private internals +bundle_resolver = getattr(resolver, "_bundle", resolver) +activator = getattr(bundle_resolver, "_activator", None) + +# GOOD: Use or request a public API +activator = resolver.get_activator() +``` + +**Key insight**: If you can't do something through the public interface, the fix is to extend the interface—not bypass it. + +**Test**: *"Would this code break if the internal implementation changed?"* + --- ## The Golden Rule