Skip to content

Commit eb6f66f

Browse files
docs: add encapsulation boundary rules (Principle 7)
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>
1 parent a344a1c commit eb6f66f

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

context/PYTHON_BEST_PRACTICES.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,29 @@ from .config import load_config
9898
- Group with blank lines between sections
9999
- Combine `from x import a, b` for related items only
100100

101+
### 7. Respect Encapsulation Boundaries
102+
103+
**Never access private attributes (`_name`) from outside a class.** Private attributes are implementation details that can change without notice.
104+
105+
| Pattern | Problem | Correct Approach |
106+
|---------|---------|------------------|
107+
| `getattr(obj, "_internal", None)` | Bypasses encapsulation | Request a public API |
108+
| `obj._private_attr` | Depends on implementation | Use protocol/interface |
109+
| Chained unwrapping | Compounds fragility | Expose capability at top level |
110+
111+
```python
112+
# BAD: Reaching into private internals
113+
bundle_resolver = getattr(resolver, "_bundle", resolver)
114+
activator = getattr(bundle_resolver, "_activator", None)
115+
116+
# GOOD: Use or request a public API
117+
activator = resolver.get_activator()
118+
```
119+
120+
**Key insight**: If you can't do something through the public interface, the fix is to extend the interface—not bypass it.
121+
122+
**Test**: *"Would this code break if the internal implementation changed?"*
123+
101124
---
102125

103126
## The Golden Rule

0 commit comments

Comments
 (0)