Isolate Unix and Windows Service Boundaries
Core idea
Some standard modules are platform-specific. pwd exposes Unix user-account information, termios controls POSIX terminals and winreg accesses the Windows registry. Hide such dependencies behind a small adapter, detect support before using it, and define a clear unavailable outcome. Import availability is not evidence of permissions or operational correctness.
from importlib.util import find_specfor name in ('pwd', 'termios', 'winreg'): print(name, find_spec(name) is not None)Observed on this Linux runtime, not a universal Unix or Windows promise. No user records or registry contents are read.
Expected output:
pwd Truetermios Truewinreg FalseTest capability-based dispatch
def choose_backend(available): if 'winreg' in available: return 'registry' if 'pwd' in available: return 'account lookup' return 'unsupported'for names in ({'winreg'}, {'pwd'}, set()): print(choose_backend(names))Synthetic capability sets test selection independently of host OS. Actual backend operations still need target-specific tests.
Expected output:
registryaccount lookupunsupportedCommon mistake
Do not import winreg unconditionally in a portable module. Catch expected capability errors narrowly; do not silently turn permission failures into unsupported-platform results.
Practice
Design a capability adapter for one read-only OS operation. Test unsupported and permission-denied cases with fakes; execute the real adapter only on a suitable authorized target.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Platform-specific services
Check your understanding of platform-specific services.
What is printed?
from importlib.util import find_specprint(find_spec('winreg') is None)What is printed?
def supported(names): return 'pwd' in namesprint(supported(set()))Which module exposes Windows registry access?
What must an operational adapter test include beyond module presence?