what makes you different, why you, competitive advantage, differentiators
**Chip Foundry Services stands out through our unique combination** of **comprehensive services, technical excellence, and customer-first approach** — offering complete solutions from design to production under one roof (eliminating coordination headaches), 95%+ first-silicon success rate (vs 60-70% industry average), flexible terms for startups to Fortune 500, and 40+ years of semiconductor expertise with 10,000+ successful tape-outs. Unlike pure-play foundries (fabrication only) or design houses (design only), we provide integrated services reducing time-to-market by 3-6 months and total costs by 20-30% through optimized design-for-manufacturing, streamlined communication, and single-point accountability. Our startup program has helped 500+ companies bring first chips to market with flexible payment terms, technical mentorship, and 20% NRE discounts, while enterprise customers benefit from dedicated teams, priority scheduling, and long-term partnerships with major technology companies trusting us for critical chip development.
**Why-Why Analysis** is **an iterative questioning technique that traces symptom chains toward underlying causes** - It is a core method in modern semiconductor quality governance and continuous-improvement workflows.
**What Is Why-Why Analysis?**
- **Definition**: an iterative questioning technique that traces symptom chains toward underlying causes.
- **Core Mechanism**: Successive why questions decompose immediate failures into deeper causal layers.
- **Operational Scope**: It is applied in semiconductor manufacturing operations to improve audit rigor, corrective-action effectiveness, and structured project execution.
- **Failure Modes**: Linear questioning can oversimplify multi-causal failures in complex operations.
**Why Why-Why Analysis Matters**
- **Outcome Quality**: Better methods improve decision reliability, efficiency, and measurable impact.
- **Risk Management**: Structured controls reduce instability, bias loops, and hidden failure modes.
- **Operational Efficiency**: Well-calibrated methods lower rework and accelerate learning cycles.
- **Strategic Alignment**: Clear metrics connect technical actions to business and sustainability goals.
- **Scalable Deployment**: Robust approaches transfer effectively across domains and operating conditions.
**How It Is Used in Practice**
- **Method Selection**: Choose approaches by risk profile, implementation complexity, and measurable impact.
- **Calibration**: Use why-why with evidence checkpoints and branch analysis when multiple causal paths exist.
- **Validation**: Track objective metrics, compliance rates, and operational outcomes through recurring controlled reviews.
Why-Why Analysis is **a high-impact method for resilient semiconductor operations execution** - It offers a fast structured approach for initial root-cause exploration.
WID (Within-Die Variation)
Overview
Within-die variation describes parameter differences across a single die, caused by systematic process gradients and random device-level fluctuations. At advanced nodes, WID variation is the dominant source of circuit performance spread.
Sources of WID Variation
- Systematic (Spatial): Gradual parameter gradients across the die caused by CMP dishing, etch loading, lithography lens aberrations, and deposition non-uniformity. Predictable and partially correctable.
- Random (Stochastic): Statistical fluctuations at the individual device level—random dopant fluctuation (RDF), line edge roughness (LER), metal grain granularity. Unpredictable, sets fundamental limits.
Key Parameters Affected
- Vt (Threshold Voltage): σ(Vt) = AVT / √(W×L), where AVT is the Pelgrom coefficient. Smaller devices → larger Vt spread.
- Channel Length (Leff): LER causes random Leff variation ≈ 1-2nm (3σ). Significant when nominal Lgate < 20nm.
- Film Thickness: CMP-induced thickness variation across die (100-300mm scale) affects transistor and interconnect performance.
Impact
- SRAM Yield: 6T SRAM cells require matched transistor pairs. WID Vt variation limits minimum operating voltage (Vmin) and cell stability.
- Timing: Circuit speed variation across the die causes timing guard-banding, reducing effective frequency.
- Analog Matching: Current mirrors, differential pairs, and DAC/ADC elements require tight device matching.
Mitigation
- Statistical Design: Guard-band for 3σ or 6σ variation in timing and power.
- Layout Techniques: Common-centroid layout, dummy devices, symmetric orientation for matched transistor pairs.
- Process Improvement: Reduce LER (EUV lithography), improve CMP uniformity, reduce RDF (undoped channels in FinFET/GAA).
Wide bandgap (WBG) power semiconductors, gallium nitride (GaN) High-Electron-Mobility Transistors (HEMT), and silicon carbide (4H-SiC) power MOSFETs constitute the foundational energy-conversion device technologies replacing silicon in high-voltage, high-frequency, and high-temperature electrical systems. As modern power electronics transition toward high-density electric vehicle (EV) traction inverters, data center power supply units (PSU), solar inverters, and 5G RF transmitters, conventional silicon power MOSFETs and Insulated Gate Bipolar Transistors (IGBT) encounter physical efficiency ceilings dictated by silicon's narrow bandgap ($1.12\text{ eV}$) and low critical breakdown electric field ($0.3\text{ MV/cm}$). Wide bandgap semiconductors possess bandgaps exceeding $3.0\text{ eV}$ and critical electric fields greater than $3.0\text{ MV/cm}$, enabling devices to withstand kilovolt blocking voltages across ten-times thinner drift regions. Leveraging spontaneous and piezoelectric polarization, GaN HEMTs form undoped two-dimensional electron gases (2DEG) with extraordinary electron mobilities ($> 2000\text{ cm}^2/\text{V}\cdot\text{s}$), while SiC power MOSFETs deliver superior thermal conductivity and avalanche ruggedness in $800\text{V}\text{ to }1200\text{V}$ power distribution grids.
**Spontaneous and piezoelectric polarization charges create an ultra-conductive two-dimensional electron gas at the AlGaN/GaN heterojunction.** Unlike silicon MOSFETs that require heavy chemical dopant implantation to populate the conduction channel, a gallium nitride HEMT forms a conductive channel spontaneously. When a thin layer of aluminum gallium nitride ($\text{Al}_x\text{Ga}_{1-x}\text{N}$, $x \approx 0.25$) is epitaxially grown via MOCVD atop a GaN buffer layer, the non-centrosymmetric wurtzite crystal structure generates strong spontaneous polarization ($P_{\text{sp}}$), while the lattice mismatch generates tensile strain that produces powerful piezoelectric polarization ($P_{\text{pz}}$). The resulting net polarization charge gradient ($\sigma_{\text{pol}} = P_{\text{total}}(\text{AlGaN}) - P_{\text{total}}(\text{GaN})$) induces an abrupt triangular potential quantum well at the interface, accumulating a dense sheet of electrons ($n_s$) without intentional impurity doping:
$$
n_s = \frac{\sigma_{\text{pol}}}{q} - \left( \frac{\epsilon}{q d} \right) \left( q\phi_b + E_F - \Delta E_c \right) \approx 10^{13}\text{ cm}^{-2},
$$
where $d$ is barrier thickness, $q\phi_b$ is surface barrier height, and $\Delta E_c$ is conduction band offset. Because the channel is completely free of ionized dopant impurities, ionized impurity scattering is eliminated, yielding an electron mobility ($\mu_n > 2000\text{ cm}^2/\text{V}\cdot\text{s}$) that is three times higher than bulk silicon.
**The Baliga Figure of Merit demonstrates how extreme critical electric breakdown fields slash specific on-resistance in power drift layers.** In unipolar power semiconductor switches, the minimum specific on-resistance ($R_{\text{on,sp}}$, in $\text{m}\Omega\cdot\text{cm}^2$) required to block a target breakdown voltage ($V_{\text{BR}}$) is fundamentally bounded by the Baliga Figure of Merit ($\text{BFOM} = \epsilon_s \mu_n E_{\text{crit}}^3$):
$$
R_{\text{on,sp}} = \frac{4 V_{\text{BR}}^2}{\epsilon_s \mu_n E_{\text{crit}}^3} = \frac{4 V_{\text{BR}}^2}{\text{BFOM}}.
$$
Because the critical electric field of 4H-SiC ($3.0\text{ MV/cm}$) and GaN ($3.3\text{ MV/cm}$) is ten times higher than that of silicon ($0.3\text{ MV/cm}$), the drift layer thickness can be reduced by a factor of ten, and the drift doping concentration can be increased by a factor of one hundred. Consequently, 4H-SiC and GaN devices achieve theoretical $\text{BFOM}$ values that are respectively $500\times$ and $2000\times$ greater than silicon, allowing a $650\text{V}$ GaN transistor or $1200\text{V}$ SiC MOSFET to operate with orders-of-magnitude lower conduction loss and die area.
| Semiconductor Material | Bandgap Energy ($E_g$) | Critical Breakdown Field ($E_{\text{crit}}$) | Electron Mobility ($\mu_n$) | Baliga FOM (Relative to Silicon) | Maximum Junction Temperature ($T_{j,\max}$) | Primary Power Electronics Application |
|---|---|---|---|---|---|---|
| Silicon ($\text{Si}$) | $1.12\text{ eV}$ | $0.3\text{ MV/cm}$ | $1,400\text{ cm}^2/\text{V}\cdot\text{s}$ | $1.0\times$ | $150^\circ\text{C}$ | Low-voltage computing, legacy switches |
| Gallium Arsenide ($\text{GaAs}$) | $1.42\text{ eV}$ | $0.4\text{ MV/cm}$ | $8,500\text{ cm}^2/\text{V}\cdot\text{s}$ | $15.0\times$ | $175^\circ\text{C}$ | RF power amplifiers, optoelectronics |
| 4H-Silicon Carbide ($4\text{H-SiC}$) | $3.26\text{ eV}$ | $3.0\text{ MV/cm}$ | $900\text{ cm}^2/\text{V}\cdot\text{s}$ | $500\times$ | $> 200^\circ\text{C}$ | $800\text{V}\text{--}1200\text{V}$ EV inverters, grid converters |
| Gallium Nitride ($\text{GaN}$) | $3.40\text{ eV}$ | $3.3\text{ MV/cm}$ | $2,000\text{ cm}^2/\text{V}\cdot\text{s}$ (2DEG) | $2,000\times$ | $> 200^\circ\text{C}$ | $650\text{V}$ PSUs, fast chargers, 5G RF |
| Diamond ($\text{C}$) | $5.47\text{ eV}$ | $10.0\text{ MV/cm}$ | $2,200\text{ cm}^2/\text{V}\cdot\text{s}$ | $25,000\times$ | $> 300^\circ\text{C}$ | Ultra-high-voltage pulsed research devices |
**Enhancement-mode p-GaN gate engineering transforms depletion-mode channels into fail-safe normally-off power switches.** Because the 2DEG forms spontaneously, native AlGaN/GaN HEMTs are normally-on (depletion-mode) devices with negative threshold voltages ($V_{\text{th}} \approx -3\text{V}\text{ to }-5\text{V}$), posing catastrophic short-circuit hazards during power-up in bridge inverter topologies. To achieve fail-safe normally-off (enhancement-mode) operation, foundries deposit a p-type magnesium-doped GaN ($\text{p-GaN}$) layer directly beneath the gate electrode. The built-in potential of the $\text{p-GaN/AlGaN}$ junction lifts the conduction band energy above the Fermi level at zero gate bias, completely depleting the 2DEG channel beneath the gate and shifting the threshold voltage to a positive value ($V_{\text{th}} \approx +1.5\text{V}\text{ to }+2.0\text{V}$). Applying a positive gate bias ($V_{\text{GS}} \approx 5\text{--}6\text{V}$) pulls the conduction band back below the Fermi level, restoring the continuous, ultra-low-resistance 2DEG channel between source and drain.
**Silicon carbide trench MOSFETs integrate deep p-shielding to protect gate oxides in high-voltage electric vehicle traction inverters.** In planar SiC MOSFETs, high electric fields at the surface dielectric interface can exceed the dielectric breakdown limit of silicon dioxide ($E_{\text{ox}} > 8\text{ MV/cm}$), causing premature gate dielectric degradation. Modern industrial SiC power switches transition to vertical double-trench architectures: the gate trench is etched into the sidewall to eliminate the planar JFET resistance, while a deeper source trench incorporates heavy p-doped shielding regions beneath the trench corners. Under high drain blocking voltages ($> 1200\text{V}$), the deep p-shield forms an electrostatic depletion barrier that clamps the maximum electric field inside the gate oxide below $3\text{ MV/cm}$, ensuring multi-decade automotive reliability in $800\text{V}$ EV traction inverters operating at junction temperatures exceeding $175^\circ\text{C}$.
```flowchart
st=>start: Engineered Substrate: GaN-on-Si / GaN-on-SiC or 4H-SiC monocrystalline wafer
epi_growth=>operation: MOCVD Epitaxial Heterostructure: grow AlN nucleation + GaN buffer + AlGaN barrier (2DEG formation)
pgan_gate=>operation: E-Mode p-GaN Gate Formation: deposit & self-align p-type GaN cap to set positive threshold (Vth > +1.5V)
ohmic_contact=>operation: Low-Resistance Ohmic Metallization: Ti/Al/Ni/Au alloy anneal forms direct source/drain contacts
passivation_fp=>operation: Field Plate & SiN Passivation: multi-layer field plates suppress dynamic RDS(on) current collapse
pass=>end: WBG Power Switch Certified: V_BR > 650V/1200V with 99% conversion efficiency & AEC-Q101 qualification
st->epi_growth->pgan_gate->ohmic_contact->passivation_fp->pass
```
**Delivering ultra-high power conversion efficiency and extreme power density across next-generation electrification platforms requires evaluating device physics through a wide-bandgap-gan-sic-and-power-semiconductor lens.** By uniting MOCVD epitaxial heterojunction polarization, high-mobility 2DEG channel transport, Baliga figure of merit drift scaling, enhancement-mode p-GaN gate electrostatics, and shielded SiC trench architecture, power engineering teams achieve unprecedented power conversion performance. Mastering wide bandgap physical principles guarantees that electric vehicle traction powertrains, AI data center high-efficiency power supplies, and renewable energy grid inverters minimize energy loss, reduce thermal cooling volume, and operate with maximum robustness across mission-critical operating environments.
**Wide and Deep** is **a hybrid recommendation model that combines memorization-focused linear features with deep generalization networks** - Wide features capture known cross terms while deep layers learn latent interaction structure from embeddings.
**What Is Wide and Deep?**
- **Definition**: A hybrid recommendation model that combines memorization-focused linear features with deep generalization networks.
- **Core Mechanism**: Wide features capture known cross terms while deep layers learn latent interaction structure from embeddings.
- **Operational Scope**: It is used in speech and recommendation pipelines to improve prediction quality, system efficiency, and production reliability.
- **Failure Modes**: Overweighting wide terms can reduce generalization to unseen combinations.
**Why Wide and Deep Matters**
- **Performance Quality**: Better models improve recognition, ranking accuracy, and user-relevant output quality.
- **Efficiency**: Scalable methods reduce latency and compute cost in real-time and high-traffic systems.
- **Risk Control**: Diagnostic-driven tuning lowers instability and mitigates silent failure modes.
- **User Experience**: Reliable personalization and robust speech handling improve trust and engagement.
- **Scalable Deployment**: Strong methods generalize across domains, users, and operational conditions.
**How It Is Used in Practice**
- **Method Selection**: Choose techniques by data sparsity, latency limits, and target business objectives.
- **Calibration**: Calibrate loss weights between wide and deep branches using online-offline consistency checks.
- **Validation**: Track objective metrics, robustness indicators, and online-offline consistency over repeated evaluations.
Wide and Deep is **a high-impact component in modern speech and recommendation machine-learning systems** - It balances memorization and generalization in large-scale ranking systems.
**Wide I/O** is an **early 3D-stacked DRAM standard designed for mobile applications that placed memory directly on top of the logic processor** — using a 512-bit wide interface with TSV connections to achieve high bandwidth at low power, representing an important precursor to HBM that demonstrated the viability of 3D memory stacking but was ultimately superseded by LPDDR and HBM for mobile and high-performance applications respectively.
**What Is Wide I/O?**
- **Definition**: A JEDEC-standardized (JESD229) 3D-stacked DRAM interface designed for mobile SoCs — specifying a 512-bit wide data bus, 4 independent 128-bit channels, and TSV-based vertical connections between the DRAM die and the logic die below it, targeting low-power mobile applications.
- **Package-on-Package (PoP) Alternative**: Wide I/O was designed to replace the PoP (Package-on-Package) memory stacking used in smartphones — where a DRAM package is stacked on top of the processor package using standard BGA connections.
- **Wide I/O 2**: The second generation (JESD229-2) doubled the interface to 1024 bits across 8 channels, increased speed to 1067 Mbps/pin, and supported stacking up to 4 DRAM dies — targeting 68 GB/s bandwidth at < 1W power.
- **Direct Stacking**: Unlike HBM which sits beside the processor on an interposer, Wide I/O was designed for direct die-on-die stacking — the DRAM die bonded directly on top of the processor die using TSVs through the processor.
**Why Wide I/O Matters Historically**
- **3D Memory Pioneer**: Wide I/O was one of the first JEDEC standards for 3D-stacked memory with TSVs, establishing the technical foundations (TSV design rules, thermal management, testing methodology) that HBM later built upon.
- **Mobile Bandwidth Vision**: Wide I/O demonstrated that wide parallel interfaces could deliver high bandwidth at low power for mobile — the concept of trading pin speed for bus width to save energy influenced HBM's architecture.
- **Thermal Challenge Discovery**: Stacking DRAM directly on top of a hot processor die revealed the fundamental thermal conflict — processor heat degrades DRAM retention time, requiring either thermal isolation or reduced processor power, a lesson that shaped HBM's side-by-side interposer placement.
- **Market Outcome**: Wide I/O was never widely adopted — LPDDR4/5 achieved sufficient bandwidth for mobile through higher pin speeds without requiring TSVs, and HBM captured the high-bandwidth market for compute accelerators.
**Wide I/O vs. Alternatives**
| Parameter | Wide I/O 2 | LPDDR5 | HBM2 |
|-----------|-----------|--------|------|
| Interface Width | 1024 bits | 32 bits | 1024 bits |
| Pin Speed | 1067 Mbps | 6400 Mbps | 2000 Mbps |
| BW per Device | 68 GB/s | 25.6 GB/s | 256 GB/s |
| Power | < 1W | ~1-2W | ~4-5W |
| Stacking | On-logic (3D) | PoP/discrete | On-interposer (2.5D) |
| TSVs Required | Yes (in logic die) | No | Yes (in DRAM + interposer) |
| Target | Mobile SoC | Mobile SoC | GPU/HPC |
| Market Status | Not adopted | Mainstream | Mainstream |
**Wide I/O is the pioneering 3D-stacked memory standard that proved the concept but lost the market** — demonstrating that TSV-based wide parallel memory interfaces could deliver high bandwidth at low power, while revealing the thermal challenges of direct die-on-die stacking that led the industry to adopt HBM's interposer-based side-by-side architecture for high-performance applications and LPDDR's simpler packaging for mobile.
**Wide-IO** is **a wide-bus low-power memory interface strategy designed to increase throughput through parallelism rather than very high clock rate** - It is a core method in modern engineering execution workflows.
**What Is Wide-IO?**
- **Definition**: a wide-bus low-power memory interface strategy designed to increase throughput through parallelism rather than very high clock rate.
- **Core Mechanism**: Many parallel signal lines reduce per-line speed demands while delivering useful aggregate bandwidth at lower voltage.
- **Operational Scope**: It is applied in advanced semiconductor integration and AI workflow engineering to improve robustness, execution quality, and measurable system outcomes.
- **Failure Modes**: Routing and integration complexity can offset gains if physical design is not optimized.
**Why Wide-IO Matters**
- **Outcome Quality**: Better methods improve decision reliability, efficiency, and measurable impact.
- **Risk Management**: Structured controls reduce instability, bias loops, and hidden failure modes.
- **Operational Efficiency**: Well-calibrated methods lower rework and accelerate learning cycles.
- **Strategic Alignment**: Clear metrics connect technical actions to business and sustainability goals.
- **Scalable Deployment**: Robust approaches transfer effectively across domains and operating conditions.
**How It Is Used in Practice**
- **Method Selection**: Choose approaches by risk profile, implementation complexity, and measurable impact.
- **Calibration**: Balance bus width, floorplan constraints, and power targets in early architecture planning.
- **Validation**: Track objective metrics, trend stability, and cross-functional evidence through recurring controlled reviews.
Wide-IO is **a high-impact method for resilient execution** - It is a valuable option for bandwidth-sensitive low-power system designs.
**Wide metal rules** are **special design rules** that apply to metal features exceeding a specified width threshold — addressing the unique manufacturing, reliability, and performance challenges that arise when metal conductors are significantly wider than minimum-width wires.
**Why Wide Metal Needs Special Rules**
- Standard metal design rules are optimized for **minimum-width** routing used in signal interconnects.
- Wide metal features (power straps, bus lines, ground planes, I/O pads) behave differently during manufacturing:
- **CMP**: Wide features dishing more aggressively → need slotting rules.
- **Etch**: Wide features etch differently from narrow lines (different etch bias, edge effects).
- **Stress**: Large metal areas create more thermal stress → potential cracking, delamination, or via popping.
- **Electromigration**: Current distribution in wide features is non-uniform — current crowding at corners and width transitions.
**Typical Wide Metal Rules**
- **Slotting Requirements**: Insert slots when width exceeds a threshold (typically 10–20 µm) — see slot rules.
- **Maximum Width without Slots**: Hard limit on how wide an unslotted metal feature can be.
- **Increased Spacing**: Wide metal may require **larger spacing** to adjacent features than minimum-width wires — due to etch proximity effects and reliability concerns.
- **Enclosure Rules**: Via landing pads on wide metal may require different enclosure than on minimum-width wires.
- **Corner Rounding**: Sharp 90° corners in wide metal create stress concentrations — corner rounding requirements reduce cracking risk.
- **Width Transition**: Rules for transitioning from wide to narrow metal (taper angle, minimum taper length) to avoid abrupt width changes that cause etch and current density issues.
- **Minimum Area**: Even wide metal features must meet minimum enclosed area requirements.
**Impact on Power Grid Design**
- Power grid straps are the primary wide metal features.
- Wide metal rules constrain how power straps are designed:
- Cannot simply make straps as wide as desired — must comply with slotting.
- Spacing to adjacent signal routes must account for wide metal spacing rules.
- Corner-turning in power grids requires compliance with corner rules.
- Width changes (e.g., from wide strap to narrow via landing) must follow taper rules.
**Electromigration in Wide Metal**
- Current density in wide metal is **not uniform** — it concentrates at edges, corners, and via connections.
- EM checking for wide metal must account for local current density, not just average current density.
- Via placement along wide metal must ensure current is distributed evenly.
Wide metal rules are **critical for power integrity and reliability** — they ensure that the widest, most current-carrying features on the chip are manufactured with consistent quality and adequate lifetime.
**Width Multiplier** is **a scaling parameter that uniformly adjusts channel counts across a neural network** - It offers a simple knob for trading off accuracy against compute and memory.
**What Is Width Multiplier?**
- **Definition**: a scaling parameter that uniformly adjusts channel counts across a neural network.
- **Core Mechanism**: Channel dimensions are scaled by a global factor to create smaller or larger model variants.
- **Operational Scope**: It is applied in model-optimization workflows to improve efficiency, scalability, and long-term performance outcomes.
- **Failure Modes**: Very small multipliers can create bottlenecks and underfit complex data.
**Why Width Multiplier Matters**
- **Outcome Quality**: Better methods improve decision reliability, efficiency, and measurable impact.
- **Risk Management**: Structured controls reduce instability, bias loops, and hidden failure modes.
- **Operational Efficiency**: Well-calibrated methods lower rework and accelerate learning cycles.
- **Strategic Alignment**: Clear metrics connect technical actions to business and sustainability goals.
- **Scalable Deployment**: Robust approaches transfer effectively across domains and operating conditions.
**How It Is Used in Practice**
- **Method Selection**: Choose approaches by latency targets, memory budgets, and acceptable accuracy tradeoffs.
- **Calibration**: Select multiplier values from device-constrained accuracy-latency frontiers.
- **Validation**: Track accuracy, latency, memory, and energy metrics through recurring controlled evaluations.
Width Multiplier is **a high-impact method for resilient model-optimization execution** - It is a practical control for deploying right-sized model variants.
**Wigner D-Matrix** is **rotation matrices for irreducible representation spaces used to transform equivariant feature channels** - They provide the exact linear action of 3D rotations on angular feature components.
**What Is Wigner D-Matrix?**
- **Definition**: rotation matrices for irreducible representation spaces used to transform equivariant feature channels.
- **Core Mechanism**: For each degree, feature vectors are multiplied by D matrices parameterized by rotation angles.
- **Operational Scope**: It is applied in graph-neural-network systems to improve robustness, accountability, and long-term performance outcomes.
- **Failure Modes**: Numerical instability at high degrees can corrupt orthogonality and symmetry behavior.
**Why Wigner D-Matrix Matters**
- **Outcome Quality**: Better methods improve decision reliability, efficiency, and measurable impact.
- **Risk Management**: Structured controls reduce instability, bias loops, and hidden failure modes.
- **Operational Efficiency**: Well-calibrated methods lower rework and accelerate learning cycles.
- **Strategic Alignment**: Clear metrics connect technical actions to business and sustainability goals.
- **Scalable Deployment**: Robust approaches transfer effectively across domains and operating conditions.
**How It Is Used in Practice**
- **Method Selection**: Choose approaches by uncertainty level, data availability, and performance objectives.
- **Calibration**: Use stable parameterizations, precomputation, and orthogonality checks across sampled rotations.
- **Validation**: Track quality, stability, and objective metrics through recurring controlled evaluations.
Wigner D-Matrix is **a high-impact method for resilient graph-neural-network execution** - They are the operational backbone of rotation-consistent geometric feature transport.
**Wilcoxon Signed-Rank** is **a non-parametric paired-sample test that evaluates median shift in matched observations** - It is a core method in modern semiconductor statistical experimentation and reliability analysis workflows.
**What Is Wilcoxon Signed-Rank?**
- **Definition**: a non-parametric paired-sample test that evaluates median shift in matched observations.
- **Core Mechanism**: Signed ranks of paired differences capture directional change without normality dependence.
- **Operational Scope**: It is applied in semiconductor manufacturing operations to improve experimental rigor, statistical inference quality, and decision confidence.
- **Failure Modes**: Zero-heavy or improperly paired data can reduce sensitivity and distort interpretation.
**Why Wilcoxon Signed-Rank Matters**
- **Outcome Quality**: Better methods improve decision reliability, efficiency, and measurable impact.
- **Risk Management**: Structured controls reduce instability, bias loops, and hidden failure modes.
- **Operational Efficiency**: Well-calibrated methods lower rework and accelerate learning cycles.
- **Strategic Alignment**: Clear metrics connect technical actions to business and sustainability goals.
- **Scalable Deployment**: Robust approaches transfer effectively across domains and operating conditions.
**How It Is Used in Practice**
- **Method Selection**: Choose approaches by risk profile, implementation complexity, and measurable impact.
- **Calibration**: Validate pairing and assess difference structure before choosing Wilcoxon analysis.
- **Validation**: Track objective metrics, compliance rates, and operational outcomes through recurring controlled reviews.
Wilcoxon Signed-Rank is **a high-impact method for resilient semiconductor operations execution** - It is a practical alternative to paired t-tests under non-normal conditions.
**Win Rate** is **the percentage of head-to-head comparisons where one model output is preferred over another** - It is a core method in modern AI evaluation and governance execution.
**What Is Win Rate?**
- **Definition**: the percentage of head-to-head comparisons where one model output is preferred over another.
- **Core Mechanism**: Pairwise preference voting captures relative utility under blind comparative evaluation.
- **Operational Scope**: It is applied in AI evaluation, safety assurance, and model-governance workflows to improve measurement quality, comparability, and deployment decision confidence.
- **Failure Modes**: Win rates can be unstable with small sample sizes or judge bias.
**Why Win Rate Matters**
- **Outcome Quality**: Better methods improve decision reliability, efficiency, and measurable impact.
- **Risk Management**: Structured controls reduce instability, bias loops, and hidden failure modes.
- **Operational Efficiency**: Well-calibrated methods lower rework and accelerate learning cycles.
- **Strategic Alignment**: Clear metrics connect technical actions to business and sustainability goals.
- **Scalable Deployment**: Robust approaches transfer effectively across domains and operating conditions.
**How It Is Used in Practice**
- **Method Selection**: Choose approaches by risk profile, implementation complexity, and measurable impact.
- **Calibration**: Report confidence intervals and matchup coverage alongside win-rate values.
- **Validation**: Track objective metrics, compliance rates, and operational outcomes through recurring controlled reviews.
Win Rate is **a high-impact method for resilient AI execution** - It is highly useful for ranking conversational models in user-preference settings.
**Wind Power PPA** is **procurement of wind-generated electricity through long-term power purchase agreements** - It secures renewable supply and price visibility without owning generation assets.
**What Is Wind Power PPA?**
- **Definition**: procurement of wind-generated electricity through long-term power purchase agreements.
- **Core Mechanism**: Contract structures define delivered energy, settlement terms, and certificate allocation.
- **Operational Scope**: It is applied in environmental-and-sustainability programs to improve robustness, accountability, and long-term performance outcomes.
- **Failure Modes**: Contract mismatch with load profile can reduce financial and emissions benefit.
**Why Wind Power PPA Matters**
- **Outcome Quality**: Better methods improve decision reliability, efficiency, and measurable impact.
- **Risk Management**: Structured controls reduce instability, bias loops, and hidden failure modes.
- **Operational Efficiency**: Well-calibrated methods lower rework and accelerate learning cycles.
- **Strategic Alignment**: Clear metrics connect technical actions to business and sustainability goals.
- **Scalable Deployment**: Robust approaches transfer effectively across domains and operating conditions.
**How It Is Used in Practice**
- **Method Selection**: Choose approaches by compliance targets, resource intensity, and long-term sustainability objectives.
- **Calibration**: Model volume, basis risk, and market scenarios before signing long-term terms.
- **Validation**: Track resource efficiency, emissions performance, and objective metrics through recurring controlled evaluations.
Wind Power PPA is **a high-impact method for resilient environmental-and-sustainability execution** - It is a major pathway for large-scale renewable sourcing.
**Window Partition** is a **technique that divides a feature map or image into non-overlapping local windows for efficient self-attention** — computing attention independently within each window to reduce complexity from $O(N^2)$ to $O(w^2 cdot N/w^2) = O(N cdot w^2)$.
**How Does Window Partition Work?**
- **Partition**: Divide $H imes W$ feature map into $frac{H}{M} imes frac{W}{M}$ windows of size $M imes M$.
- **Reshape**: Each window becomes a $M^2 imes C$ tensor (sequence of $M^2$ tokens).
- **Attention**: Compute multi-head self-attention within each window independently.
- **Unpartition**: Reshape back to $H imes W imes C$.
**Why It Matters**
- **Linear Complexity**: Attention cost scales linearly with image size (fixed $M^2$ attention per window).
- **Local Inductive Bias**: Introduces locality similar to CNNs, which is beneficial for vision tasks.
- **Foundation**: The base operation for Swin Transformer, Focal Transformer, and other window-based ViTs.
**Window Partition** is **dividing the image into attention neighborhoods** — the fundamental operation that makes high-resolution Vision Transformers computationally practical.
python windows installation step 1, install python on windows, windows python beginner setup, python install manager windows, verify python installation, python path windows setup, python powershell setup, first python setup step
**Windows Python Setup Step 1 is to install one trusted Python runtime, open a fresh terminal, and prove that Windows resolves the commands to the installation you intended.** Do not begin with an editor, packages, notebooks, or copied project code. A clean interpreter check creates a known foundation and prevents most later “Python is not recognized,” wrong-version, wrong-`pip`, and Microsoft Store alias problems.
The current first-party path for modern Windows is the **Python Install Manager**, available from the Microsoft Store or Python.org. It manages Python runtimes and exposes `python`, `py`, and `pymanager`. The classic standalone `.exe` installer still exists for transitional and special cases, but Python’s official Windows documentation is moving users toward the install manager. This guide keeps Step 1 deliberately narrow: install, identify, and verify Python. Project folders and virtual environments belong to Step 2.
| Situation | Choose | First check |
|---|---|---|
| personal Windows 10/11 PC | official Install Manager | Python version |
| WinGet available | official Store package ID | manager version |
| Store blocked, MSIX allowed | Python.org manager | runtime list |
| work or school PC | approved IT catalog | approved command |
| server or managed deployment | documented enterprise method | explicit path |
| classic workflow required | signed Python.org installer | command owners |
| Linux-first project | Python inside WSL | Linux version |
## The outcome Step 1 must produce
At the end of this step, a newly opened PowerShell window should pass all of these checks:
```powershell
python --version
python -c "import sys; print(sys.executable)"
python -VV
python -m pip --version
```
The commands should return a Python 3 version, an executable path you recognize, complete version/build information, and a `pip` path associated with the same interpreter. The exact stable Python version will change over time; do not hard-code a version number unless a course, employer, or project explicitly requires it.
## Before installing: inspect what Windows already sees
Open **Windows Terminal** or **PowerShell** from the Start menu. Do not use an old terminal window that was open before software changes. Run:
```powershell
python --version
py list
pymanager --version
where.exe python
where.exe py
```
It is normal for some commands to fail on a computer with no Python setup. Record what happens instead of trying random fixes.
- If `python --version` prints a valid Python 3 version, Python may already be installed. Continue to the identity checks before installing anything else.
- If typing `python` opens the Microsoft Store, Windows is probably resolving an app-execution alias rather than a real runtime. Install through the approved path and retest in a fresh terminal.
- If `py` reports that it cannot open a file or behaves unlike the install manager, the legacy Python launcher may own the command.
- If `where.exe python` prints several paths, you have an ownership problem to understand before adding another installation.
- If the computer is managed by work or school, stop and use the organization’s software center or documented method.
`where.exe` reports command candidates found through the current Windows search rules. It does not prove which runtime an editor will use, but it exposes duplicate PATH entries and WindowsApps aliases early.
## Recommended path: install the Python Install Manager
### Option A — Microsoft Store
Open the Microsoft Store, search for **Python Install Manager** published by the Python Software Foundation, and select **Install**. The Store and Python.org variants provide the same install-manager capability; choose one source and stay consistent.
After installation, close every PowerShell/Terminal window and open a new one. Then run:
```powershell
pymanager --version
py list
python
```
If no runtime is present, launching `python` through the install manager can acquire the current default stable runtime. Follow the displayed prompt, allow it to finish, then exit the interactive prompt with:
```python
exit()
```
Using `pymanager` is useful in scripts or troubleshooting because an older Python launcher may already have claimed the shorter `py` command.
### Option B — WinGet
If WinGet is available, open PowerShell and install the official Store package identifier:
```powershell
winget install 9NQ7512CXL7T -e `
--accept-package-agreements
```
For automated, noninteractive provisioning, Python’s Windows documentation also shows:
```powershell
winget install 9NQ7512CXL7T -e `
--accept-package-agreements `
--disable-interactivity
```
Wait for completion, close the terminal, and open a new PowerShell window. Run:
```powershell
pymanager --version
py install --configure
python --version
```
The configuration checker can repair or explain command aliases and PATH integration. Read each requested change before accepting it, especially on a computer that already has Python installations.
### Option C — Python.org download
If the Store is unavailable but your policy permits MSIX packages, go directly to [Python’s Windows downloads page](https://www.python.org/downloads/windows/), download the Python Install Manager, verify that the publisher/signature identifies the Python Software Foundation, and install it. Do not use a third-party download portal, search advertisement, repackaged installer, or unofficial “Python bundle.”
The official [Using Python on Windows documentation](https://docs.python.org/3/using/windows.html) is the authority for current install-manager commands, advanced deployment, configuration, troubleshooting, and supported Windows versions.
## Install or select a runtime deliberately
The install manager can maintain multiple runtimes. For a first setup, the current default stable Python is usually appropriate. List local and available runtimes with:
```powershell
py list
py list --online
```
Install the default stable runtime by launching `python` when none is installed, or use the manager’s explicit installation command:
```powershell
py install
```
If a class or project requires a particular minor series, install only that declared series, for example:
```powershell
py install 3.14
```
The number above is an example, not a timeless recommendation. Use the version required by your project and confirm it is still supported. Avoid prerelease, debug, free-threaded, embeddable, or experimental packages for a first setup unless the instructions specifically call for one.
List the result again:
```powershell
py list
```
The list identifies installed tags and which runtime is currently selected. On a machine with several Python versions, use `py` version selection or an activated virtual environment rather than repeatedly rewriting PATH.
## Verify the interpreter, not just the command name
Start with a version check:
```powershell
python --version
```
Now ask the running interpreter to identify itself:
```powershell
python -c "import sys; print(sys.executable)"
python -VV
```
`sys.executable` is stronger evidence than `where.exe` because it is reported by the process that actually started. `sys.version` includes build details. On most modern Windows PCs you normally want a 64-bit interpreter, but use the architecture required by your application and hardware.
Confirm that the standard library imports:
```powershell
python -c "import ssl, sqlite3, venv"
```
Confirm that Python can execute a tiny expression:
```powershell
python -c "print(6 * 7)"
```
The expected output is:
```text
42
```
This proves command resolution, interpreter startup, parsing, execution, and terminal output. It does not yet prove that an editor, project, or third-party package is configured.
## Verify `pip` through the interpreter
Use:
```powershell
python -m pip --version
```
Prefer `python -m pip` over a bare `pip` command. It explicitly runs the `pip` module belonging to the `python` interpreter you just verified, reducing wrong-environment mistakes. The output should show a `pip` version and a path tied to the same Python runtime.
Do not install global packages during Step 1. In Step 2, create a project virtual environment and install packages inside it. Global package installation makes tutorials appear to work while hiding dependency conflicts and interpreter-selection errors.
## Understand `python`, `py`, and `pymanager`
`python` launches the selected runtime or the active virtual environment. It is the command most tutorials and cross-platform tools expect.
`py` is the convenient Windows command for listing, selecting, installing, and launching managed Python runtimes. On older machines it may instead refer to the legacy launcher, so inspect its behavior.
`pymanager` names the new install manager unambiguously. Use it when `py` is ambiguous or when automating install-manager actions.
These commands are related, but they are not guaranteed to be the same executable. The acceptance test is that they identify a coherent installation and that `python` runs the intended interpreter.
## PATH: verify first, edit last
PATH is an ordered list of directories Windows searches for commands. Adding many Python and `Scripts` directories does not make setup more reliable; it often makes command selection unpredictable.
Inspect candidates with:
```powershell
where.exe python
where.exe pip
Get-Command python -All
Get-Command py -All
```
If the Python Install Manager is installed but its commands are unavailable, first close and reopen Terminal. Then open **Manage app execution aliases** from the Start menu and confirm the Python default and install-manager aliases are enabled. Check that the user PATH still includes the WindowsApps location documented by Python.
Do not paste an unfamiliar PATH string into system settings. Do not delete existing entries blindly. User PATH changes normally affect your account; system PATH changes affect every user and often require administrator approval.
## The Microsoft Store alias trap
Windows may include `python.exe` and `python3.exe` app-execution aliases that redirect an unconfigured command to the Store. This is a discovery feature, not proof that Python is installed.
If `python` opens the Store after you installed the manager:
1. Close all terminals and open a fresh PowerShell window.
2. Test `pymanager --version` and `py list`.
3. Open **Manage app execution aliases**.
4. Refresh the aliases by disabling and re-enabling the Python default and install-manager entries.
5. Confirm the documented per-user WindowsApps directory remains in PATH.
6. Run `where.exe python` and `python -c "import sys; print(sys.executable)"` again.
Do not solve an alias problem by downloading a second unrelated Python distribution.
## Legacy launcher conflicts
The older Python Launcher for Windows also uses `py`. If `pymanager` works but `py` behaves differently, open **Installed apps**, locate **Python Launcher**, and inspect whether the legacy launcher is still required by existing workflows. Python’s current documentation recommends removing the old launcher when adopting the install manager because both compete for `py`.
Before removing anything on a shared or managed computer, confirm ownership and policy. Existing automation may depend on the legacy launcher. The safe goal is one documented command owner, not aggressive cleanup.
## Classic installer fallback
Use the traditional executable installer only when your course, organization, supported Python version, operating environment, or deployment method explicitly requires it. Download it from Python.org, verify the signature/publisher, and choose the 64-bit installer for a typical modern x64 PC.
For a personal machine, a per-user installation avoids unnecessary system-wide changes. If the installer presents PATH and launcher choices, decide them intentionally:
- Adding `python.exe` to PATH makes `python` available in new terminals but can compete with other installations.
- Installing the launcher assigns the `py` command and may conflict with the newer install manager.
- “Install for all users” changes machine-wide state and usually needs administrator rights.
- A custom location is useful only when a real policy or tool requires it.
After installation, close the installer and all terminal windows. Open a new PowerShell window and repeat the complete acceptance checks. Never assume that “Setup was successful” proves command ownership.
## Windows Python is not WSL Python
PowerShell and Command Prompt run Windows executables. A WSL shell runs Linux executables inside a Linux distribution. Each environment has its own Python, package manager, paths, permissions, and virtual environments.
If your course or project is Linux-first, open the WSL distribution and follow its Linux package guidance there. Do not create a virtual environment with Windows Python and activate it inside WSL, or vice versa. Decide the execution environment first and keep the project toolchain inside it.
## Managed work and school computers
Application control, proxy inspection, Store restrictions, certificate policy, antivirus, roaming profiles and limited PATH permissions can change installation behavior. Use the approved software center, internal package repository or IT request. Record the required Python series and architecture rather than asking for “any Python.”
Do not disable endpoint security, bypass proxy controls, install from a personal mirror, or elevate with unapproved credentials. A reproducible approved install is more valuable than a locally clever workaround.
## Common failures and targeted fixes
**“Python was not found” or `python` opens the Store.** Verify the install manager, refresh app-execution aliases, reopen Terminal, inspect WindowsApps in PATH, and try `pymanager`/`py`.
**`py` says it cannot open a file.** The legacy launcher may be receiving an install-manager subcommand. Test `pymanager` and inspect Installed Apps for Python Launcher.
**`python` and `py` report different versions.** Run `py list`, `where.exe python`, `Get-Command python -All`, and `sys.executable`. Remove or reconfigure only the installation you have positively identified as unwanted.
**`pip` is not recognized.** Test `python -m pip --version`. A bare `pip` shortcut is optional; the module command is the reliable form. Package installation belongs in a virtual environment in Step 2.
**The terminal still sees the old result.** Environment and alias changes are captured when processes start. Close all terminal and editor windows and open a new PowerShell session.
**The installer needs administrator access.** Prefer a supported per-user path or the approved organization method. Do not run an installer as administrator merely because troubleshooting instructions online say so.
**An editor cannot find Python even though PowerShell can.** Step 1 is complete at the operating-system level. Restart the editor, then explicitly select the interpreter during the editor setup step; do not reinstall Python.
## What not to do in Step 1
- Do not install Anaconda, Miniconda, the Store runtime, a Python.org classic installer, and a third-party version manager all at once.
- Do not install packages globally with `pip install ...`.
- Do not copy random Python or `Scripts` folders into PATH.
- Do not rename `python.exe` or move a managed runtime directory.
- Do not use `sudo`, Linux package commands, or WSL paths in PowerShell.
- Do not disable security controls to make an installer run.
- Do not choose a prerelease build for a beginner setup.
- Do not assume the Python version embedded in a screenshot remains current.
| Gate | Pass condition | If it fails |
|---|---|---|
| trusted source | approved publisher | cancel and reacquire |
| version | supported Python 3 | inspect manager |
| identity | recognized runtime path | inspect duplicates |
| architecture | matches requirement | select correct build |
| standard library | imports cleanly | repair trusted install |
| package frontend | same interpreter | use module form |
| manager inventory | understood default | resolve ownership |
| fresh session | same result repeats | fix alias or PATH |
## Record the Step 1 result
Save the output of these commands in your course notes, setup ticket, or project README:
```powershell
python --version
python -c "import sys; print(sys.executable)"
python -m pip --version
py list
```
Do not record usernames or unrelated private paths in a public repository. The useful facts are the Python series, architecture, installation method, selected executable, and date verified.
## Step 1 completion gate
Step 1 is complete only when a **new PowerShell session** launches the intended Python, `sys.executable` identifies it, the standard library imports, and `python -m pip --version` points to the same installation. If any of those checks is ambiguous, fix ownership before proceeding.
The next step is to create a project directory and a `.venv`, activate it, and prove that project-local `python` and `pip` replace the global interpreter for that terminal session. Do not compensate for a failed Step 1 by configuring an editor around the wrong executable.
**Windows Python Setup Step 1 succeeds when installation becomes evidence: one trusted source, one understood command path, one verified interpreter, and a repeatable result in a fresh terminal.**
windows python step 10, python setup step 10 windows
**Windows Python Setup Step 10 is Automated dependency updates: produce a reviewable dependency-update policy that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **each update arrives as a tested, narrow pull request**. The main failure to design against is **merging version churn without release-note or compatibility review**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | Automated dependency updates behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 10 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 10 boundary
The deliverable is **reviewable dependency-update policy**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns Automated dependency updates. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "Automated dependency updates"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the Automated dependency updates policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 10 exercise command is:
```powershell
python -m pip list --outdated
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 10 threat review must directly address **merging version churn without release-note or compatibility review**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to Automated dependency updates. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 10
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 10 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | reviewable dependency-update policy exists in reviewed source | machine-only hidden state |
| normal behavior | each update arrives as a tested, narrow pull request | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses merging version churn without release-note or compatibility review | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 10 completion gate
Step 10 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m pip list --outdated
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 11 continues with **Environment variables**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 10 succeeds when each update arrives as a tested, narrow pull request, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 100, python setup step 100 windows
**Windows Python Setup Step 100 is Lifecycle maintenance: produce a scheduled runtime and dependency maintenance that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **supported versions, updates, deprecations, and tests have owners**. The main failure to design against is **letting an apparently stable environment become unsupported**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | Lifecycle maintenance behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 100 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 100 boundary
The deliverable is **scheduled runtime and dependency maintenance**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns Lifecycle maintenance. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "Lifecycle maintenance"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the Lifecycle maintenance policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 100 exercise command is:
```powershell
python -m pip list --outdated
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 100 threat review must directly address **letting an apparently stable environment become unsupported**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to Lifecycle maintenance. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 100
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 100 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | scheduled runtime and dependency maintenance exists in reviewed source | machine-only hidden state |
| normal behavior | supported versions, updates, deprecations, and tests have owners | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses letting an apparently stable environment become unsupported | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 100 completion gate
Step 100 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m pip list --outdated
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 101 continues with **Production readiness capstone**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 100 succeeds when supported versions, updates, deprecations, and tests have owners, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 101, python setup step 101 windows
**Windows Python Setup Step 101 is Production readiness capstone: produce a signed-off Windows Python operating dossier that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **build, test, security, deployment, rollback, restore, and operations gates all pass**. The main failure to design against is **declaring production ready without evidence or accountable owners**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | Production readiness capstone behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 101 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 101 boundary
The deliverable is **signed-off Windows Python operating dossier**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns Production readiness capstone. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "Production readiness capstone"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the Production readiness capstone policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 101 exercise command is:
```powershell
python .\quality_gate.py
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 101 threat review must directly address **declaring production ready without evidence or accountable owners**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to Production readiness capstone. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 101
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 101 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | signed-off Windows Python operating dossier exists in reviewed source | machine-only hidden state |
| normal behavior | build, test, security, deployment, rollback, restore, and operations gates all pass | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses declaring production ready without evidence or accountable owners | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 101 completion gate
Step 101 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
This is the capstone: keep the dossier current as the system, team, dependencies, and risks change.
**Windows Python Setup Step 101 succeeds when build, test, security, deployment, rollback, restore, and operations gates all pass, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 11, python setup step 11 windows
**Windows Python Setup Step 11 is Environment variables: produce a typed application configuration boundary that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **required values are validated without logging secrets**. The main failure to design against is **depending on invisible machine-wide state**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | Environment variables behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 11 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 11 boundary
The deliverable is **typed application configuration boundary**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns Environment variables. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "Environment variables"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the Environment variables policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 11 exercise command is:
```powershell
Get-ChildItem Env:
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 11 threat review must directly address **depending on invisible machine-wide state**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to Environment variables. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 11
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 11 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | typed application configuration boundary exists in reviewed source | machine-only hidden state |
| normal behavior | required values are validated without logging secrets | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses depending on invisible machine-wide state | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 11 completion gate
Step 11 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
Get-ChildItem Env:
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 12 continues with **Secret handling**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 11 succeeds when required values are validated without logging secrets, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 12, python setup step 12 windows
**Windows Python Setup Step 12 is Secret handling: produce a local secret injection and redaction policy that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **missing secrets fail closed and present secrets never appear in logs**. The main failure to design against is **committing tokens or passing them on command lines**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | Secret handling behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 12 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 12 boundary
The deliverable is **local secret injection and redaction policy**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns Secret handling. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "Secret handling"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the Secret handling policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 12 exercise command is:
```powershell
python -c "import os; print('set' if os.getenv('APP_TOKEN') else 'missing')"
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 12 threat review must directly address **committing tokens or passing them on command lines**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to Secret handling. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 12
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 12 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | local secret injection and redaction policy exists in reviewed source | machine-only hidden state |
| normal behavior | missing secrets fail closed and present secrets never appear in logs | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses committing tokens or passing them on command lines | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 12 completion gate
Step 12 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -c "import os; print('set' if os.getenv('APP_TOKEN') else 'missing')"
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 13 continues with **Application logging**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 12 succeeds when missing secrets fail closed and present secrets never appear in logs, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 13, python setup step 13 windows
**Windows Python Setup Step 13 is Application logging: produce a structured rotating application logs that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **levels, fields, rotation, and redaction behave under tests**. The main failure to design against is **logging sensitive payloads or creating unbounded files**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | Application logging behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 13 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 13 boundary
The deliverable is **structured rotating application logs**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns Application logging. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "Application logging"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the Application logging policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 13 exercise command is:
```powershell
python -m pytest tests\test_logging.py
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 13 threat review must directly address **logging sensitive payloads or creating unbounded files**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to Application logging. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 13
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 13 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | structured rotating application logs exists in reviewed source | machine-only hidden state |
| normal behavior | levels, fields, rotation, and redaction behave under tests | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses logging sensitive payloads or creating unbounded files | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 13 completion gate
Step 13 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m pytest tests\test_logging.py
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 14 continues with **Debugger workflow**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 13 succeeds when levels, fields, rotation, and redaction behave under tests, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 14, python setup step 14 windows
**Windows Python Setup Step 14 is Debugger workflow: produce a repeatable VS Code and debugpy launch contract that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **breakpoints bind to the selected interpreter and source**. The main failure to design against is **opening an unauthenticated debugger to a network**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | Debugger workflow behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 14 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 14 boundary
The deliverable is **repeatable VS Code and debugpy launch contract**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns Debugger workflow. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "Debugger workflow"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the Debugger workflow policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 14 exercise command is:
```powershell
python -m debugpy --listen 127.0.0.1:5678 app.py
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 14 threat review must directly address **opening an unauthenticated debugger to a network**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to Debugger workflow. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 14
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 14 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | repeatable VS Code and debugpy launch contract exists in reviewed source | machine-only hidden state |
| normal behavior | breakpoints bind to the selected interpreter and source | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses opening an unauthenticated debugger to a network | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 14 completion gate
Step 14 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m debugpy --listen 127.0.0.1:5678 app.py
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 15 continues with **Pathlib and file paths**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 14 succeeds when breakpoints bind to the selected interpreter and source, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 15, python setup step 15 windows
**Windows Python Setup Step 15 is Pathlib and file paths: produce a portable project path layer that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **paths work outside the developer working directory**. The main failure to design against is **hard-coded drive letters and string-concatenated paths**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | Pathlib and file paths behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 15 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 15 boundary
The deliverable is **portable project path layer**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns Pathlib and file paths. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "Pathlib and file paths"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the Pathlib and file paths policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 15 exercise command is:
```powershell
python -m pytest tests\test_paths.py
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 15 threat review must directly address **hard-coded drive letters and string-concatenated paths**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to Pathlib and file paths. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 15
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 15 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | portable project path layer exists in reviewed source | machine-only hidden state |
| normal behavior | paths work outside the developer working directory | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses hard-coded drive letters and string-concatenated paths | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 15 completion gate
Step 15 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m pytest tests\test_paths.py
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 16 continues with **Text encoding and Unicode**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 15 succeeds when paths work outside the developer working directory, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 16, python setup step 16 windows
**Windows Python Setup Step 16 is Text encoding and Unicode: produce a explicit UTF-8 text boundary that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **round trips preserve non-ASCII text and malformed input is handled**. The main failure to design against is **relying on the current Windows code page**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | Text encoding and Unicode behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 16 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 16 boundary
The deliverable is **explicit UTF-8 text boundary**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns Text encoding and Unicode. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "Text encoding and Unicode"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the Text encoding and Unicode policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 16 exercise command is:
```powershell
python -X utf8 -m pytest tests\test_text_io.py
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 16 threat review must directly address **relying on the current Windows code page**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to Text encoding and Unicode. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 16
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 16 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | explicit UTF-8 text boundary exists in reviewed source | machine-only hidden state |
| normal behavior | round trips preserve non-ASCII text and malformed input is handled | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses relying on the current Windows code page | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 16 completion gate
Step 16 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -X utf8 -m pytest tests\test_text_io.py
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 17 continues with **JSON and CSV data**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 16 succeeds when round trips preserve non-ASCII text and malformed input is handled, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 17, python setup step 17 windows
**Windows Python Setup Step 17 is JSON and CSV data: produce a validated JSON and newline-safe CSV adapters that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **round trips, schemas, delimiters, and failures are deterministic**. The main failure to design against is **trusting unvalidated external fields**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | JSON and CSV data behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 17 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 17 boundary
The deliverable is **validated JSON and newline-safe CSV adapters**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns JSON and CSV data. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "JSON and CSV data"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the JSON and CSV data policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 17 exercise command is:
```powershell
python -m pytest tests\test_serialization.py
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 17 threat review must directly address **trusting unvalidated external fields**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to JSON and CSV data. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 17
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 17 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | validated JSON and newline-safe CSV adapters exists in reviewed source | machine-only hidden state |
| normal behavior | round trips, schemas, delimiters, and failures are deterministic | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses trusting unvalidated external fields | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 17 completion gate
Step 17 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m pytest tests\test_serialization.py
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 18 continues with **HTTP client basics**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 17 succeeds when round trips, schemas, delimiters, and failures are deterministic, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 18, python setup step 18 windows
**Windows Python Setup Step 18 is HTTP client basics: produce a bounded HTTP client adapter that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **status, headers, decoding, and error mapping are tested offline**. The main failure to design against is **making live internet calls in unit tests**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | HTTP client basics behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 18 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 18 boundary
The deliverable is **bounded HTTP client adapter**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns HTTP client basics. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "HTTP client basics"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the HTTP client basics policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 18 exercise command is:
```powershell
python -m pytest tests\test_http_client.py
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 18 threat review must directly address **making live internet calls in unit tests**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to HTTP client basics. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 18
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 18 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | bounded HTTP client adapter exists in reviewed source | machine-only hidden state |
| normal behavior | status, headers, decoding, and error mapping are tested offline | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses making live internet calls in unit tests | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 18 completion gate
Step 18 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m pytest tests\test_http_client.py
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 19 continues with **Timeouts and retries**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 18 succeeds when status, headers, decoding, and error mapping are tested offline, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 19, python setup step 19 windows
**Windows Python Setup Step 19 is Timeouts and retries: produce a explicit retry budget with backoff that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **transient failures retry within a time budget and permanent failures stop**. The main failure to design against is **retry storms and duplicate side effects**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | Timeouts and retries behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 19 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 19 boundary
The deliverable is **explicit retry budget with backoff**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns Timeouts and retries. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "Timeouts and retries"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the Timeouts and retries policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 19 exercise command is:
```powershell
python -m pytest tests\test_retry_policy.py
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 19 threat review must directly address **retry storms and duplicate side effects**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to Timeouts and retries. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 19
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 19 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | explicit retry budget with backoff exists in reviewed source | machine-only hidden state |
| normal behavior | transient failures retry within a time budget and permanent failures stop | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses retry storms and duplicate side effects | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 19 completion gate
Step 19 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m pytest tests\test_retry_policy.py
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 20 continues with **Command-line interfaces**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 19 succeeds when transient failures retry within a time budget and permanent failures stop, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
**Windows Python Setup Step 2 is to create one project directory, build a project-local `.venv`, activate or explicitly invoke it, and prove that both Python and `pip` now belong to that environment.** Step 1 established a trusted global runtime. Step 2 prevents one project’s packages from silently changing another project—or the Python installation itself.
A virtual environment is a lightweight Python installation context with its own interpreter entry points and `site-packages` directory. It is not a virtual machine, container, security sandbox, or copy of Windows. The `.venv` directory records a relationship to the base Python used to create it, so it should be reproducible and disposable rather than copied between computers or committed to source control.
| Situation | Step 2 choice | Proof |
|---|---|---|
| new personal project | create local `.venv` | project-local executable |
| existing cloned project | follow its setup file | declared dependencies install |
| several Python versions | choose base first | expected runtime version |
| PowerShell activation allowed | run `Activate.ps1` | prompt and executable change |
| activation blocked by policy | call venv Python directly | explicit local executable |
| Command Prompt preferred | use batch activation | `where.exe python` changes |
| WSL project | create Linux venv in WSL | Linux path, not Windows path |
## Step 2 prerequisites
Open a **new PowerShell window** and confirm Step 1 still passes:
```powershell
python --version
python -c "import sys; print(sys.executable)"
python -m pip --version
```
If any command fails or points to an unintended installation, return to Step 1. Do not create a virtual environment from an interpreter you cannot identify.
For a course or existing repository, read `README`, `pyproject.toml`, `.python-version`, `requirements.txt`, or organization instructions before choosing the Python series. The project may require a specific runtime or environment tool. Do not replace an established Poetry, uv, Conda, Hatch, or corporate workflow with this tutorial.
## Choose a safe project location
Use a normal user-owned development directory. Avoid Windows system directories, `Program Files`, the Python installation directory, an email attachment location, and a folder controlled by another tool. Cloud-synced directories can work, but simultaneous synchronization of thousands of `.venv` files may be slow or conflict-prone.
Create a parent folder and project folder:
```powershell
New-Item -ItemType Directory `
-Path "$HOME\Projects" `
-Force
Set-Location "$HOME\Projects"
New-Item -ItemType Directory `
-Path "hello-python" `
-Force
Set-Location "hello-python"
```
Confirm the current location:
```powershell
Get-Location
```
The remaining commands assume PowerShell is inside the project root. A virtual environment created in the wrong directory is not dangerous, but it creates confusion and is easy to use accidentally.
## Record the base interpreter
Before creating `.venv`, record the runtime that will seed it:
```powershell
python --version
python -c "import sys; print(sys.executable)"
```
If several managed runtimes exist, use the Python Install Manager to inspect them:
```powershell
py list
```
Then use the selected runtime explicitly if the project requires it. The exact selector depends on the required Python series. Do not choose a prerelease or experimental runtime merely because it appears newest.
## Create `.venv`
Run:
```powershell
python -m venv .venv
```
This invokes the standard-library `venv` module with the verified base interpreter. By default it creates the directory, writes `pyvenv.cfg`, installs environment-specific executable entry points, and bootstraps `pip` unless `--without-pip` was requested.
Wait for the command to return. A successful creation may print nothing. Verify the important files without opening or editing them:
```powershell
Test-Path .\.venv\pyvenv.cfg
Test-Path .\.venv\Scripts\python.exe
Test-Path .\.venv\Scripts\Activate.ps1
```
Each command should print `True`. If creation stops with a traceback, diagnose that error rather than manually constructing `.venv` folders.
## What `.venv` contains
On Windows, the environment normally contains:
- `pyvenv.cfg`, which identifies the base installation and environment settings.
- `Scripts\python.exe`, the project-local Python entry point.
- `Scripts\pip.exe` and related console commands when `pip` is bootstrapped.
- `Scripts\Activate.ps1`, the PowerShell activation script.
- `Lib\site-packages`, the environment’s third-party package location.
Treat the entire directory as generated state. Do not edit `pyvenv.cfg` to fake a different Python version. Do not move the environment to another project or computer. Recreate it from declared dependencies.
## Activate in PowerShell
From the project root, run exactly:
```powershell
.\.venv\Scripts\Activate.ps1
```
PowerShell’s `.` and leading backslash mean “the current directory.” Activation modifies the current shell session so commands such as `python` and package-installed tools resolve through `.venv\Scripts` first. Many prompts add `(.venv)`, but prompt decoration is not proof by itself.
Activation must run in the shell you plan to use. Launching the script in a separate process would change that child process and then discard the change. Opening a new Terminal tab also creates a new session that is not automatically activated.
## Prove activation with interpreter identity
Run:
```powershell
python --version
python -c "import sys; print(sys.executable)"
python -m pip --version
```
The executable path should end inside the project’s `.venv\Scripts` directory. The `pip` path should point inside the same `.venv`. This identity check is the Step 2 gate.
Inspect command resolution if needed:
```powershell
Get-Command python
where.exe python
$env:VIRTUAL_ENV
```
The environment variable should identify the current `.venv`. `where.exe` may list more than one candidate; the first active command and `sys.executable` determine what actually ran.
## Activation is convenience, not a requirement
You can use the environment without activation by invoking its interpreter directly:
```powershell
.\.venv\Scripts\python.exe --version
.\.venv\Scripts\python.exe -c "import sys; print(sys.executable)"
.\.venv\Scripts\python.exe -m pip --version
```
This explicit path is valuable for automation, scheduled tasks, managed machines, and troubleshooting. It also proves that a PowerShell activation-policy error does not mean the virtual environment is broken.
The line continuation above belongs to PowerShell commands whose executable path is already complete. The canonical interpreter-identity command when activation is working remains the exact single line:
```powershell
python -c "import sys; print(sys.executable)"
```
## If PowerShell blocks `Activate.ps1`
An error stating that scripts are disabled is an execution-policy decision, not a Python installation failure. Inspect all policy scopes:
```powershell
Get-ExecutionPolicy -List
```
Group Policy scopes can override user choices. On a work or school computer, do not bypass policy; use the explicit `.venv\Scripts\python.exe` commands or contact the administrator.
On a personal computer, if you understand and approve the change, Python’s official `venv` documentation gives this current-user command:
```powershell
Set-ExecutionPolicy `
-ExecutionPolicy RemoteSigned `
-Scope CurrentUser
```
Read PowerShell’s prompt before confirming, then rerun:
```powershell
.\.venv\Scripts\Activate.ps1
```
Do not use `Unrestricted`, disable organization policy, or change `LocalMachine` merely to activate a local environment. Execution policy is a script-control safety feature, not an obstacle to erase. The explicit interpreter path remains available without any policy change.
## Command Prompt and other shells use different scripts
Activation syntax belongs to the shell, not to Python generally.
In **Command Prompt**:
```bat
.venv\Scripts\activate.bat
```
In **PowerShell**:
```powershell
.\.venv\Scripts\Activate.ps1
```
Do not paste `source .venv/bin/activate` into PowerShell; that is a Unix-style command and path. Git Bash, WSL, Command Prompt, and PowerShell are different shells. A project may be stored on the same disk yet require shell-specific activation syntax.
## Upgrade `pip` inside the environment only when needed
After activation and identity verification, inspect `pip`:
```powershell
python -m pip --version
```
If project instructions require an update, run it inside the active environment:
```powershell
python -m pip install --upgrade pip
```
Use `python -m pip`, not a bare `pip`, so the package operation is explicitly tied to the verified interpreter. An update needs network access to the configured package index and may be governed by proxy or organization policy.
Step 2 does not require installing a large framework. Isolation can be proven using the environment’s paths and an empty package list. Avoid adding arbitrary packages merely as a test.
## Inspect environment-local packages
Run:
```powershell
python -m pip list
```
A new environment normally has a small set of packaging tools. Exact contents depend on Python and `venv` behavior; for example, modern Python no longer guarantees that `setuptools` is installed by default. Do not treat a screenshot from an older tutorial as the required package list.
Confirm the environment’s package directory:
```powershell
python -c "import site; print(site.getsitepackages())"
```
The result should point into `.venv`. This verifies package isolation without installing anything.
## Create one small program
Use a text editor to create `hello.py` in the project root with:
```python
import sys
print("Hello from Step 2")
print(sys.executable)
```
Run it from the activated PowerShell session:
```powershell
python .\hello.py
```
The first line should print the message and the second should identify the `.venv` interpreter. This proves the project file, working directory, active command, and runtime agree.
Do not double-click `hello.py` in File Explorer as the verification method. File association may launch another interpreter in a transient window. Run scripts explicitly from the project terminal.
## Add `.venv` to version-control exclusions
Virtual environments contain generated executables and packages that are large, platform-specific, and often include machine paths. Do not commit `.venv`.
If the project uses Git, ensure its `.gitignore` contains:
```gitignore
.venv/
```
Recent Python versions may create an ignore file within a new environment, but keep the project-level exclusion explicit when collaborating or supporting multiple Python versions.
Before the first commit, check:
```powershell
git status
```
If Git is not installed, skip this command. Version control is not required to prove the environment.
## Deactivate cleanly
Run:
```powershell
deactivate
```
Then verify that the global interpreter is selected again:
```powershell
python -c "import sys; print(sys.executable)"
```
Deactivation changes only the current shell. It does not delete `.venv`, uninstall packages, or change another terminal window.
Reactivate from the project root whenever you return:
```powershell
.\.venv\Scripts\Activate.ps1
```
## Recreating an environment
A virtual environment is disposable. If it was created with the wrong Python, corrupted, or moved, deactivate it, close programs using it, remove it through an approved recoverable method, and run `python -m venv .venv` again from the correct base interpreter. Do not manually copy missing executables from another environment.
Deleting `.venv` also deletes packages installed only there. Source code should remain outside `.venv`; dependency declarations should make recreation possible. Before deleting a mature environment, confirm the project has an authoritative dependency file.
## Dependency declarations come after isolation
For a simple tutorial, Step 3 may install a package and record it. Real projects may use `pyproject.toml`, lock files, requirements files, or a higher-level environment manager. Follow the project’s chosen source of truth.
`python -m pip freeze` reports the current environment, including transitive dependencies. It is not automatically the best design for a new project and should not replace a deliberate dependency workflow.
## Common failures and targeted fixes
**`.venv` was created in the wrong folder.** Run `Get-Location`, deactivate if necessary, and create the environment in the actual project root. Do not move the existing environment.
**The prompt says `(.venv)` but Python is global.** Prompt text can be stale or customized. Trust `python -c "import sys; print(sys.executable)"`; reactivate from the correct directory.
**Activation is blocked.** Inspect `Get-ExecutionPolicy -List`. On managed systems use the explicit local interpreter or contact IT. On a personal system consider the documented current-user `RemoteSigned` setting only after understanding it.
**`python -m venv .venv` uses the wrong Python series.** Deactivate, identify the required base with `py list`, recreate from the correct interpreter, and reverify.
**`pip` installs globally.** Stop. Run the identity and `python -m pip --version` checks. Activate correctly or call `.venv\Scripts\python.exe -m pip` explicitly.
**An editor selects another interpreter.** The environment is still valid. Restart the editor if needed and choose the project `.venv` interpreter explicitly during editor setup.
**A package build requests C++ tools.** Environment isolation is working; the package may lack a compatible wheel. Do not install a compiler blindly. Check the project’s supported Python version, architecture, package documentation, and organization policy.
**The environment works in one terminal but not another.** Activation is per-shell. Activate separately in every new terminal or use the explicit interpreter path.
**A copied `.venv` fails on another PC.** Recreate it there from the declared Python and dependencies. Virtual environments are not portable deployment artifacts.
## What not to do in Step 2
- Do not run package installs before verifying `sys.executable` and `pip` ownership.
- Do not create `.venv` inside another virtual environment unintentionally.
- Do not commit `.venv` to Git.
- Do not move or rename an active environment and expect its scripts to repair themselves.
- Do not use global `pip install` to work around activation.
- Do not set PowerShell execution policy to `Unrestricted` for this tutorial.
- Do not mix Windows and WSL virtual environments.
- Do not run activation scripts downloaded from an untrusted project.
- Do not assume prompt decoration proves isolation.
| Step 2 gate | Pass condition | If it fails |
|---|---|---|
| project root | intended folder | change location |
| base runtime | required Python | select correct base |
| environment files | three checks are `True` | recreate `.venv` |
| local interpreter | path is inside `.venv` | reactivate or use explicit path |
| local `pip` | path is inside `.venv` | use interpreter module form |
| isolation | site path is local | inspect environment ownership |
| script run | reports local Python | run from project terminal |
| deactivation | global path returns | close or reset shell |
## Step 2 completion gate
Step 2 is complete when all of the following are true:
1. PowerShell is in the intended project root.
2. `.venv` was created by the intended Python runtime.
3. `python -c "import sys; print(sys.executable)"` reports the project-local interpreter after activation—or the environment’s explicit `python.exe` runs correctly without activation.
4. `python -m pip --version` reports the same environment.
5. `hello.py` runs through that interpreter.
6. `.venv/` is excluded from version control.
7. `deactivate` returns the shell to the global interpreter.
Record these commands and results in private setup notes or the appropriate project documentation:
```powershell
Get-Location
python --version
python -c "import sys; print(sys.executable)"
python -m pip --version
```
Do not publish private usernames or unrelated filesystem details. The useful facts are the project, Python series, environment name, creation method, and verification date.
The next step can install the project’s first declared dependency, run a reproducible import check, and record dependencies using the project’s chosen packaging workflow. Do not proceed until interpreter and package ownership are unambiguous.
**Windows Python Setup Step 2 succeeds when the project has a disposable `.venv` and the running interpreter proves that both code and packages are isolated there.**
windows python step 20, python setup step 20 windows
**Windows Python Setup Step 20 is Command-line interfaces: produce a documented argparse command interface that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **help, exit codes, stdout, and stderr form a stable contract**. The main failure to design against is **breaking automation with ambiguous output or silent failures**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | Command-line interfaces behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 20 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 20 boundary
The deliverable is **documented argparse command interface**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns Command-line interfaces. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "Command-line interfaces"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the Command-line interfaces policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 20 exercise command is:
```powershell
python -m app --help
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 20 threat review must directly address **breaking automation with ambiguous output or silent failures**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to Command-line interfaces. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 20
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 20 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | documented argparse command interface exists in reviewed source | machine-only hidden state |
| normal behavior | help, exit codes, stdout, and stderr form a stable contract | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses breaking automation with ambiguous output or silent failures | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 20 completion gate
Step 20 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m app --help
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 21 continues with **Subprocess safety**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 20 succeeds when help, exit codes, stdout, and stderr form a stable contract, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 21, python setup step 21 windows
**Windows Python Setup Step 21 is Subprocess safety: produce a argument-list subprocess wrapper that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **exit codes, timeouts, text encoding, and captured output are controlled**. The main failure to design against is **shell injection and hung child processes**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | Subprocess safety behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 21 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 21 boundary
The deliverable is **argument-list subprocess wrapper**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns Subprocess safety. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "Subprocess safety"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the Subprocess safety policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 21 exercise command is:
```powershell
python -m pytest tests\test_process_runner.py
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 21 threat review must directly address **shell injection and hung child processes**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to Subprocess safety. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 21
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 21 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | argument-list subprocess wrapper exists in reviewed source | machine-only hidden state |
| normal behavior | exit codes, timeouts, text encoding, and captured output are controlled | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses shell injection and hung child processes | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 21 completion gate
Step 21 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m pytest tests\test_process_runner.py
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 22 continues with **Project packaging**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 21 succeeds when exit codes, timeouts, text encoding, and captured output are controlled, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 22, python setup step 22 windows
**Windows Python Setup Step 22 is Project packaging: produce a installable pyproject-based package that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **imports and console entry points work outside the source directory**. The main failure to design against is **confusing the working tree with an installed distribution**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | Project packaging behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 22 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 22 boundary
The deliverable is **installable pyproject-based package**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns Project packaging. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "Project packaging"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the Project packaging policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 22 exercise command is:
```powershell
python -m pip install -e .
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 22 threat review must directly address **confusing the working tree with an installed distribution**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to Project packaging. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 22
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 22 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | installable pyproject-based package exists in reviewed source | machine-only hidden state |
| normal behavior | imports and console entry points work outside the source directory | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses confusing the working tree with an installed distribution | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 22 completion gate
Step 22 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m pip install -e .
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 23 continues with **Imports and module layout**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 22 succeeds when imports and console entry points work outside the source directory, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 23, python setup step 23 windows
**Windows Python Setup Step 23 is Imports and module layout: produce a src-layout import boundary that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **tests import the installed package rather than accidental local files**. The main failure to design against is **shadowing standard or third-party modules**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | Imports and module layout behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 23 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 23 boundary
The deliverable is **src-layout import boundary**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns Imports and module layout. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "Imports and module layout"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the Imports and module layout policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 23 exercise command is:
```powershell
python -m pytest
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 23 threat review must directly address **shadowing standard or third-party modules**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to Imports and module layout. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 23
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 23 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | src-layout import boundary exists in reviewed source | machine-only hidden state |
| normal behavior | tests import the installed package rather than accidental local files | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses shadowing standard or third-party modules | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 23 completion gate
Step 23 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m pytest
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 24 continues with **Advanced type checking**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 23 succeeds when tests import the installed package rather than accidental local files, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 24, python setup step 24 windows
**Windows Python Setup Step 24 is Advanced type checking: produce a typed public boundaries and narrowed values that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **owned modules pass with justified, narrow exceptions**. The main failure to design against is **mass ignores that create unchecked regions**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | Advanced type checking behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 24 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 24 boundary
The deliverable is **typed public boundaries and narrowed values**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns Advanced type checking. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "Advanced type checking"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the Advanced type checking policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 24 exercise command is:
```powershell
python -m mypy
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 24 threat review must directly address **mass ignores that create unchecked regions**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to Advanced type checking. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 24
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 24 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | typed public boundaries and narrowed values exists in reviewed source | machine-only hidden state |
| normal behavior | owned modules pass with justified, narrow exceptions | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses mass ignores that create unchecked regions | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 24 completion gate
Step 24 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m mypy
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 25 continues with **Dataclasses and domain models**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 24 succeeds when owned modules pass with justified, narrow exceptions, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 25, python setup step 25 windows
**Windows Python Setup Step 25 is Dataclasses and domain models: produce a validated immutable value objects that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **construction, equality, serialization, and invalid values are tested**. The main failure to design against is **mistaking type hints for runtime validation**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | Dataclasses and domain models behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 25 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 25 boundary
The deliverable is **validated immutable value objects**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns Dataclasses and domain models. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "Dataclasses and domain models"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the Dataclasses and domain models policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 25 exercise command is:
```powershell
python -m pytest tests\test_models.py
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 25 threat review must directly address **mistaking type hints for runtime validation**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to Dataclasses and domain models. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 25
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 25 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | validated immutable value objects exists in reviewed source | machine-only hidden state |
| normal behavior | construction, equality, serialization, and invalid values are tested | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses mistaking type hints for runtime validation | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 25 completion gate
Step 25 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m pytest tests\test_models.py
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 26 continues with **Exception design**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 25 succeeds when construction, equality, serialization, and invalid values are tested, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 26, python setup step 26 windows
**Windows Python Setup Step 26 is Exception design: produce a small documented exception hierarchy that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **callers can distinguish recoverable, input, and system failures**. The main failure to design against is **catching Exception broadly and losing context**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | Exception design behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 26 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 26 boundary
The deliverable is **small documented exception hierarchy**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns Exception design. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "Exception design"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the Exception design policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 26 exercise command is:
```powershell
python -m pytest tests\test_errors.py
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 26 threat review must directly address **catching Exception broadly and losing context**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to Exception design. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 26
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 26 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | small documented exception hierarchy exists in reviewed source | machine-only hidden state |
| normal behavior | callers can distinguish recoverable, input, and system failures | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses catching Exception broadly and losing context | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 26 completion gate
Step 26 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m pytest tests\test_errors.py
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 27 continues with **Context managers**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 26 succeeds when callers can distinguish recoverable, input, and system failures, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 27, python setup step 27 windows
**Windows Python Setup Step 27 is Context managers: produce a deterministic resource cleanup that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **resources close on success, failure, and cancellation paths**. The main failure to design against is **leaking files, locks, sockets, or transactions**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | Context managers behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 27 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 27 boundary
The deliverable is **deterministic resource cleanup**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns Context managers. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "Context managers"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the Context managers policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 27 exercise command is:
```powershell
python -m pytest tests\test_resources.py
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 27 threat review must directly address **leaking files, locks, sockets, or transactions**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to Context managers. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 27
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 27 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | deterministic resource cleanup exists in reviewed source | machine-only hidden state |
| normal behavior | resources close on success, failure, and cancellation paths | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses leaking files, locks, sockets, or transactions | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 27 completion gate
Step 27 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m pytest tests\test_resources.py
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 28 continues with **Iterators and generators**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 27 succeeds when resources close on success, failure, and cancellation paths, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 28, python setup step 28 windows
**Windows Python Setup Step 28 is Iterators and generators: produce a streaming data pipeline that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **large inputs are consumed lazily with defined exhaustion behavior**. The main failure to design against is **retaining entire datasets or hiding generator failures**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | Iterators and generators behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 28 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 28 boundary
The deliverable is **streaming data pipeline**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns Iterators and generators. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "Iterators and generators"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the Iterators and generators policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 28 exercise command is:
```powershell
python -m pytest tests\test_streaming.py
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 28 threat review must directly address **retaining entire datasets or hiding generator failures**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to Iterators and generators. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 28
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 28 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | streaming data pipeline exists in reviewed source | machine-only hidden state |
| normal behavior | large inputs are consumed lazily with defined exhaustion behavior | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses retaining entire datasets or hiding generator failures | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 28 completion gate
Step 28 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m pytest tests\test_streaming.py
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 29 continues with **Asyncio foundations**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 28 succeeds when large inputs are consumed lazily with defined exhaustion behavior, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 29, python setup step 29 windows
**Windows Python Setup Step 29 is Asyncio foundations: produce a cancellable async service boundary that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **timeouts and cancellation release resources predictably**. The main failure to design against is **blocking the event loop with synchronous work**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | Asyncio foundations behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 29 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 29 boundary
The deliverable is **cancellable async service boundary**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns Asyncio foundations. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "Asyncio foundations"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the Asyncio foundations policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 29 exercise command is:
```powershell
python -m pytest tests\test_async_service.py
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 29 threat review must directly address **blocking the event loop with synchronous work**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to Asyncio foundations. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 29
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 29 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | cancellable async service boundary exists in reviewed source | machine-only hidden state |
| normal behavior | timeouts and cancellation release resources predictably | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses blocking the event loop with synchronous work | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 29 completion gate
Step 29 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m pytest tests\test_async_service.py
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 30 continues with **Threading**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 29 succeeds when timeouts and cancellation release resources predictably, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
python windows package step 3, install package in windows venv, windows pip setup, python dependencies windows, python requirements windows, verify package install, python pip beginner setup, windows dependency workflow
**Windows Python Setup Step 3 is to install one intentional dependency inside the verified `.venv`, prove that both the distribution and imported module came from that environment, check dependency consistency, and record enough information to reproduce the result.** Step 1 established the trusted Python runtime. Step 2 established project isolation. Step 3 is where package-management discipline begins.
This tutorial uses `requests` as a small, familiar example. If you are setting up an existing repository, do **not** add `requests` unless that project declares it. Follow the repository’s `pyproject.toml`, lock file, requirements file, or documented environment tool instead. The goal is not to collect packages; it is to make one dependency traceable from request to installation to import to reproducible declaration.
| Situation | Step 3 action | Evidence |
|---|---|---|
| new tutorial project | install one example | import and metadata pass |
| existing repository | use declared install command | project checks pass |
| managed computer | use approved package index | configured source is trusted |
| package has a wheel | install compatible artifact | no local compiler needed |
| only source archive exists | stop and inspect build needs | build path is intentional |
| dependency conflict appears | read resolver output | constraints are corrected |
| repeatable exercise needed | save and test snapshot | clean environment recreates |
## Re-enter the Step 2 project
Open a fresh PowerShell window and move to the project created in Step 2:
```powershell
Set-Location "$HOME\Projects\hello-python"
Get-Location
```
Confirm that `.venv` exists:
```powershell
Test-Path .\.venv\Scripts\python.exe
```
The result should be `True`. If not, return to Step 2 and create the environment from the intended base runtime.
Activate it:
```powershell
.\.venv\Scripts\Activate.ps1
```
If PowerShell policy blocks activation, use the explicit environment interpreter shown later. Do not reinstall Python and do not install the dependency globally.
## Prove the environment before installation
Run:
```powershell
python --version
python -c "import sys; print(sys.executable)"
python -m pip --version
```
Both the interpreter and `pip` paths must point inside this project’s `.venv`. Prompt text such as `(.venv)` is convenient, but `sys.executable` is the evidence.
Inspect the starting package state:
```powershell
python -m pip list
python -m pip check
```
`pip check` should report that no broken requirements were found. Exact packaging-tool versions vary with the Python runtime and environment creation date.
## Understand the package command
Use this form:
```powershell
python -m pip install requests
```
`python -m pip` means “run the `pip` module belonging to this exact `python`.” A bare `pip install` can resolve to another environment, especially when PATH contains multiple Python tools.
The word `requests` is a **distribution name** used by the package index and installer. The corresponding Python import is also named `requests`, but distribution and import names are not always identical. Never guess an import name solely from a package’s display name.
The command asks `pip` to resolve a compatible stable release under the current Python, platform, configured index, and existing constraints. It may also install transitive dependencies required by `requests`. Those transitive packages are not automatically new direct project requirements.
## Inspect the configured package source
Before installing software on a managed or security-sensitive computer, inspect `pip` configuration:
```powershell
python -m pip config list -v
```
An ordinary personal setup may use the default Python Package Index. An employer or school may require an authenticated internal mirror. Follow organization policy and certificate/proxy configuration.
Do not copy commands that add `--trusted-host`, disable TLS verification, replace certificates, or redirect to an unknown index. Those flags can turn a network problem into a software-supply-chain problem.
Check the exact spelling of the requested distribution. Typosquatting packages intentionally resemble popular names. Obtain names from the project’s official documentation or repository rather than from an advertisement or unverified post.
## Install the tutorial dependency
For this new tutorial project, run:
```powershell
python -m pip install requests
```
Read the output. It should identify packages downloaded or already satisfied, select compatible artifacts, install them into `.venv`, and end without an error. “Successfully installed” is useful but not sufficient; complete the identity and import checks.
If the project already has a dependency declaration, stop using the tutorial package and use its documented command. Typical existing-project commands include:
```powershell
python -m pip install -r requirements.txt
```
or a project-specific editable/install command. Do not run multiple competing setup paths unless the project documentation tells you how they relate.
## Verify distribution metadata
Ask `pip` what it installed:
```powershell
python -m pip show requests
```
Review the name, version, location, requirements, and dependents. The location must be inside `.venv`. Then obtain the installed distribution version through Python’s standard metadata API:
```powershell
python -c "from importlib.metadata import version; print(version('requests'))"
```
This checks installed distribution metadata rather than relying on a package-defined `__version__` attribute, which is optional and may be deprecated or absent.
## Verify the imported module
Run:
```powershell
python -c "import requests; print(requests.__file__)"
```
The module path must point inside the same `.venv`. This catches a local file shadowing the package or an import coming from another environment.
Run a no-network functional check:
```powershell
python -c "import requests; print(requests.codes.ok)"
```
The expected value is `200`. This proves the module imports and a basic packaged constant is available without making an external request.
Avoid using a public website request as the first test. Network access introduces DNS, proxy, TLS, firewall, rate-limit, service, and privacy variables unrelated to whether the package installed correctly.
## Detect local module shadowing
Do not name your script `requests.py`, `pip.py`, `json.py`, or after another imported package. Python searches the current project path, so a local file can hide the intended module.
Inspect the project root:
```powershell
Get-ChildItem
```
If `requests.__file__` points to the project folder instead of `.venv`, rename the conflicting file and remove its generated `__pycache__` only after confirming the exact target. Then rerun the import check.
## Check dependency consistency
Run:
```powershell
python -m pip check
```
The pass result is “No broken requirements found.” A failure means an installed distribution’s declared requirement is missing or incompatible. Copy the complete message into your notes and correct the declared constraints or environment; do not blindly upgrade every package.
Inspect the environment:
```powershell
python -m pip list
python -m pip freeze
```
`pip list` is human-oriented inventory. `pip freeze` emits requirement-style lines representing installed distributions. Neither command decides which packages are direct design choices.
## Direct and transitive dependencies
`requests` is the direct dependency in this tutorial because you intentionally selected and import it. Packages installed because `requests` requires them are transitive dependencies. The distinction matters:
- Direct dependencies belong in the project’s authored dependency declaration.
- Transitive dependencies are resolved from direct constraints and may be captured by a lock or snapshot.
- Removing a direct package does not necessarily remove every transitive package because another dependency may need them.
- A raw `pip freeze` cannot explain why a package is present.
For a maintained application or library, use the project’s `pyproject.toml` and chosen lock workflow. For this bounded beginner exercise, a requirements snapshot demonstrates recreation, but it should be labeled as a snapshot rather than treated as universal packaging architecture.
## Record a reproducible tutorial snapshot
Write the current environment snapshot:
```powershell
python -m pip freeze `
| Set-Content requirements.txt
```
Inspect it:
```powershell
Get-Content requirements.txt
```
The file should contain exact installed versions for `requests` and its resolved dependencies. Commit `requirements.txt`, not `.venv`, if this tutorial project is under version control.
A freeze snapshot is most reliable when recreating the same project on a compatible Python/platform combination. Compiled packages, platform markers, Python-version constraints, and index availability can make a snapshot nonportable. Production locking may also record hashes and platform-specific solutions.
## Record the intentional dependency separately
For learning purposes, create a short direct-dependency note:
```powershell
Set-Content `
-Path requirements.in `
-Value "requests"
```
Here `requirements.in` communicates the one intentional dependency, while `requirements.txt` captures the resolved tutorial environment. Plain `pip` does not automatically compile `requirements.in`; mature projects use an explicit locking tool or `pyproject.toml` workflow. Do not invent a second source of truth in an existing repository.
Avoid adding an arbitrary exact version to `requirements.in` merely because it is installed today. Version constraints should express tested compatibility and risk policy. The generated snapshot can preserve the exact environment separately.
## Recreate in a clean verification environment
The strongest Step 3 test is a second disposable environment. From the project root, deactivate the working environment:
```powershell
deactivate
```
Create a separate verification environment:
```powershell
python -m venv .venv-check
```
Do not activate it. Install through its explicit interpreter:
```powershell
.\.venv-check\Scripts\python.exe `
-m pip install `
-r requirements.txt
```
Verify the recreated dependency with complete single-line commands:
```powershell
.\.venv-check\Scripts\python.exe -c "import requests; print(requests.__file__)"
.\.venv-check\Scripts\python.exe -m pip check
```
The import path should point inside `.venv-check`, and the dependency check should pass. Add `.venv-check/` to version-control exclusions while it exists.
This test separates “my current environment happens to work” from “the recorded dependency set can create a working environment.” It is still a same-machine test; continuous integration across supported Python versions and operating systems is a later qualification step.
## Keep both virtual environments out of Git
Ensure `.gitignore` contains:
```gitignore
.venv/
.venv-check/
```
Run:
```powershell
git status
```
Only project source and dependency declarations should appear. If Git is not installed, skip the Git commands; isolation and reproduction can still be verified.
## Use explicit paths when activation is blocked
Every Step 3 operation can be tied directly to the project environment:
```powershell
.\.venv\Scripts\python.exe -m pip install requests
.\.venv\Scripts\python.exe -m pip show requests
.\.venv\Scripts\python.exe -c "import requests; print(requests.__file__)"
```
This is safer than changing a managed PowerShell policy. Activation is a PATH convenience, not a requirement for package isolation.
## Wheels, source distributions, and compilers
A wheel is a built distribution that `pip` can install without compiling the package locally. A source distribution contains source and build metadata; installing it may invoke a build backend and require a C/C++ or Rust compiler, SDK headers, external libraries, or network access for build dependencies.
If output says it is building a wheel and then fails, do not assume Python or `.venv` is broken. Check:
- whether the package supports your Python version and Windows architecture;
- whether a compatible wheel exists;
- whether the project intentionally supports source builds;
- whether approved build tools and native libraries are installed;
- whether the configured index mirrors all required artifacts.
Do not install Visual Studio Build Tools or another compiler merely to silence a single unexplained error. For beginners, selecting a supported Python/package combination with published wheels is usually the correct path.
## Version constraints and upgrades
These forms mean different things:
```text
requests
requests==X.Y.Z
requests>=X.Y
requests>=X.Y,Windows Python Setup — Step 3: Install, Verify, Recordverified .venv → intentional dependency → metadata + import proof → consistency check → clean recreationDEPENDENCY EVIDENCE CHAIN1 · VERIFYlocal Python2 · INSTALLpython -m pip3 · IMPORTmodule path4 · CHECKrequirements5 · RECORD + RECREATEdirect intent → requirements.in or pyprojectresolved snapshot → requirements.txt or lockclean .venv-check → install · import · pip checkCommit dependency declarations; never commit the virtual environment.PACKAGE TRUST GATESCORRECT NAMEofficial project sourceTRUSTED INDEXTLS · proxy · policyLOCAL LOCATIONmodule inside .venvCONSISTENT GRAPHpip check passesEvidence before convenience.STEP 3 ACCEPTANCE CHAINvenv ownerdistributionmodule pathdependency fileclean rebuildInstalled is not reproducible until a clean environment can produce the same passing import.
| Step 3 gate | Pass condition | If it fails |
|---|---|---|
| environment owner | executable is local | reactivate `.venv` |
| package source | approved index | fix trusted configuration |
| distribution metadata | local location | reinstall through local Python |
| imported module | local module path | remove shadowing or wrong owner |
| dependency graph | `pip check` passes | correct constraints |
| declaration | direct intent is recorded | choose one source of truth |
| snapshot or lock | resolved state saved | generate intentionally |
| clean recreation | import and check pass | repair reproducibility |
## Step 3 completion gate
Step 3 is complete only when:
1. The active or explicit interpreter belongs to the project `.venv`.
2. Installation used `python -m pip` or the explicit environment interpreter.
3. Distribution metadata and imported module paths both point inside `.venv`.
4. `python -m pip check` passes.
5. The intentional dependency is distinguished from transitive dependencies.
6. A requirements snapshot or the project’s established lock/declaration is recorded.
7. A clean verification environment can install, import, and pass the dependency check.
8. Virtual-environment directories remain excluded from source control.
Record this compact evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip show requests
python -c "import requests; print(requests.__file__)"
python -m pip check
```
If this is an existing project, substitute its declared dependency and official test command. Do not publish private indexes, tokens, usernames, or unrelated filesystem paths.
The next setup step can configure an editor to select `.venv`, add a repeatable run/debug task, and confirm that the editor terminal and debugger report the same `sys.executable` as PowerShell. Editor configuration must consume this verified environment, not create a competing one silently.
**Windows Python Setup Step 3 succeeds when a dependency has an auditable chain from trusted source to local installation to local import to a clean reproducible rebuild.**
windows python step 30, python setup step 30 windows
**Windows Python Setup Step 30 is Threading: produce a bounded thread-worker design that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **shared state is synchronized and shutdown joins workers**. The main failure to design against is **races, deadlocks, and orphaned threads**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | Threading behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 30 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 30 boundary
The deliverable is **bounded thread-worker design**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns Threading. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "Threading"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the Threading policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 30 exercise command is:
```powershell
python -m pytest tests\test_threads.py
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 30 threat review must directly address **races, deadlocks, and orphaned threads**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to Threading. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 30
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 30 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | bounded thread-worker design exists in reviewed source | machine-only hidden state |
| normal behavior | shared state is synchronized and shutdown joins workers | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses races, deadlocks, and orphaned threads | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 30 completion gate
Step 30 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m pytest tests\test_threads.py
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 31 continues with **Multiprocessing**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 30 succeeds when shared state is synchronized and shutdown joins workers, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 31, python setup step 31 windows
**Windows Python Setup Step 31 is Multiprocessing: produce a spawn-safe process workers that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **Windows spawn starts cleanly and results/errors return**. The main failure to design against is **missing main guards and unpicklable work items**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | Multiprocessing behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 31 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 31 boundary
The deliverable is **spawn-safe process workers**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns Multiprocessing. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "Multiprocessing"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the Multiprocessing policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 31 exercise command is:
```powershell
python -m pytest tests\test_process_pool.py
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 31 threat review must directly address **missing main guards and unpicklable work items**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to Multiprocessing. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 31
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 31 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | spawn-safe process workers exists in reviewed source | machine-only hidden state |
| normal behavior | Windows spawn starts cleanly and results/errors return | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses missing main guards and unpicklable work items | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 31 completion gate
Step 31 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m pytest tests\test_process_pool.py
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 32 continues with **SQLite foundations**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 31 succeeds when Windows spawn starts cleanly and results/errors return, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 32, python setup step 32 windows
**Windows Python Setup Step 32 is SQLite foundations: produce a parameterized local SQLite repository that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **schema, CRUD, constraints, and temporary-database isolation pass**. The main failure to design against is **SQL injection and accidental production-file tests**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | SQLite foundations behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 32 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 32 boundary
The deliverable is **parameterized local SQLite repository**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns SQLite foundations. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "SQLite foundations"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the SQLite foundations policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 32 exercise command is:
```powershell
python -m pytest tests\test_sqlite_repository.py
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 32 threat review must directly address **SQL injection and accidental production-file tests**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to SQLite foundations. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 32
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 32 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | parameterized local SQLite repository exists in reviewed source | machine-only hidden state |
| normal behavior | schema, CRUD, constraints, and temporary-database isolation pass | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses SQL injection and accidental production-file tests | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 32 completion gate
Step 32 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m pytest tests\test_sqlite_repository.py
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 33 continues with **Database transactions**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 32 succeeds when schema, CRUD, constraints, and temporary-database isolation pass, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 33, python setup step 33 windows
**Windows Python Setup Step 33 is Database transactions: produce a atomic unit-of-work boundary that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **commit and rollback behavior survives injected failures**. The main failure to design against is **partial writes and long-held locks**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | Database transactions behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 33 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 33 boundary
The deliverable is **atomic unit-of-work boundary**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns Database transactions. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "Database transactions"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the Database transactions policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 33 exercise command is:
```powershell
python -m pytest tests\test_transactions.py
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 33 threat review must directly address **partial writes and long-held locks**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to Database transactions. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 33
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 33 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | atomic unit-of-work boundary exists in reviewed source | machine-only hidden state |
| normal behavior | commit and rollback behavior survives injected failures | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses partial writes and long-held locks | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 33 completion gate
Step 33 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m pytest tests\test_transactions.py
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 34 continues with **SQLAlchemy integration**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 33 succeeds when commit and rollback behavior survives injected failures, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 34, python setup step 34 windows
**Windows Python Setup Step 34 is SQLAlchemy integration: produce a explicit engine, session, and model lifecycle that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **sessions close and queries behave against isolated data**. The main failure to design against is **global sessions and implicit transaction ownership**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | SQLAlchemy integration behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 34 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 34 boundary
The deliverable is **explicit engine, session, and model lifecycle**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns SQLAlchemy integration. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "SQLAlchemy integration"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the SQLAlchemy integration policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 34 exercise command is:
```powershell
python -m pytest tests\test_database.py
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 34 threat review must directly address **global sessions and implicit transaction ownership**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to SQLAlchemy integration. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 34
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 34 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | explicit engine, session, and model lifecycle exists in reviewed source | machine-only hidden state |
| normal behavior | sessions close and queries behave against isolated data | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses global sessions and implicit transaction ownership | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 34 completion gate
Step 34 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m pytest tests\test_database.py
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 35 continues with **Schema migrations**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 34 succeeds when sessions close and queries behave against isolated data, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 35, python setup step 35 windows
**Windows Python Setup Step 35 is Schema migrations: produce a forward and rollback migration practice that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **a blank database upgrades and supported rollback is rehearsed**. The main failure to design against is **editing deployed migration history**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | Schema migrations behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 35 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 35 boundary
The deliverable is **forward and rollback migration practice**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns Schema migrations. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "Schema migrations"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the Schema migrations policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 35 exercise command is:
```powershell
python -m alembic current
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 35 threat review must directly address **editing deployed migration history**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to Schema migrations. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 35
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 35 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | forward and rollback migration practice exists in reviewed source | machine-only hidden state |
| normal behavior | a blank database upgrades and supported rollback is rehearsed | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses editing deployed migration history | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 35 completion gate
Step 35 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m alembic current
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 36 continues with **FastAPI service**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 35 succeeds when a blank database upgrades and supported rollback is rehearsed, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 36, python setup step 36 windows
**Windows Python Setup Step 36 is FastAPI service: produce a typed health and application API that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **health, validation, and failure responses pass client tests**. The main failure to design against is **binding development servers broadly or leaking tracebacks**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | FastAPI service behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 36 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 36 boundary
The deliverable is **typed health and application API**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns FastAPI service. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "FastAPI service"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the FastAPI service policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 36 exercise command is:
```powershell
python -m uvicorn app.main:app --reload
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 36 threat review must directly address **binding development servers broadly or leaking tracebacks**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to FastAPI service. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 36
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 36 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | typed health and application API exists in reviewed source | machine-only hidden state |
| normal behavior | health, validation, and failure responses pass client tests | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses binding development servers broadly or leaking tracebacks | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 36 completion gate
Step 36 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m uvicorn app.main:app --reload
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 37 continues with **API contract tests**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 36 succeeds when health, validation, and failure responses pass client tests, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 37, python setup step 37 windows
**Windows Python Setup Step 37 is API contract tests: produce a machine-readable endpoint contract suite that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **status codes, bodies, headers, and compatibility cases pass**. The main failure to design against is **asserting implementation details instead of public behavior**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | API contract tests behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 37 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 37 boundary
The deliverable is **machine-readable endpoint contract suite**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns API contract tests. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "API contract tests"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the API contract tests policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 37 exercise command is:
```powershell
python -m pytest tests\test_api_contract.py
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 37 threat review must directly address **asserting implementation details instead of public behavior**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to API contract tests. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 37
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 37 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | machine-readable endpoint contract suite exists in reviewed source | machine-only hidden state |
| normal behavior | status codes, bodies, headers, and compatibility cases pass | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses asserting implementation details instead of public behavior | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 37 completion gate
Step 37 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m pytest tests\test_api_contract.py
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 38 continues with **Pydantic validation**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 37 succeeds when status codes, bodies, headers, and compatibility cases pass, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 38, python setup step 38 windows
**Windows Python Setup Step 38 is Pydantic validation: produce a strict external-data models that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **coercion policy, bounds, unknown fields, and errors are explicit**. The main failure to design against is **silently accepting malformed or extra input**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | Pydantic validation behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 38 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 38 boundary
The deliverable is **strict external-data models**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns Pydantic validation. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "Pydantic validation"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the Pydantic validation policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 38 exercise command is:
```powershell
python -m pytest tests\test_validation.py
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 38 threat review must directly address **silently accepting malformed or extra input**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to Pydantic validation. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 38
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 38 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | strict external-data models exists in reviewed source | machine-only hidden state |
| normal behavior | coercion policy, bounds, unknown fields, and errors are explicit | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses silently accepting malformed or extra input | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 38 completion gate
Step 38 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m pytest tests\test_validation.py
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 39 continues with **Authentication foundations**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 38 succeeds when coercion policy, bounds, unknown fields, and errors are explicit, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
windows python step 39, python setup step 39 windows
**Windows Python Setup Step 39 is Authentication foundations: produce a hashed credential and session boundary that can be rebuilt, reviewed, tested, and operated from the verified Windows project established in Steps 1–7.** This milestone adds one bounded capability. It does not replace interpreter ownership, the project `.venv`, dependency declarations, the Step 6 quality gate, or the Step 7 clean Windows CI matrix.
The working contract is specific: **success, denial, expiry, rotation, and rate limits are tested**. The main failure to design against is **inventing cryptography or storing plaintext credentials**. Treat those as acceptance and risk statements, not optional commentary.
| Surface | Required decision | Review evidence |
|---|---|---|
| ownership | project file/module and named maintainer | diff has a clear boundary |
| interpreter | verified console Python | executable and pip agree |
| inputs | typed, bounded, and documented | invalid cases fail clearly |
| operation | Authentication foundations behavior | deterministic command/test |
| failure | explicit timeout/error/cleanup path | injected failure is observed |
| security | least privilege and redaction | no secret or unsafe default |
| CI | same non-mutating project command | clean Windows matrix passes |
| rollback | reversible change or runbook | prior behavior can be restored |
## Resume from the proven project
Open a fresh PowerShell window at the repository root:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
python -c "import sys; print(sys.executable)"
python -m pip check
python .\quality_gate.py
git status --short
```
The executable must end in the project `.venv\Scripts\python.exe`, not a global runtime or `pythonw.exe`. Every `python -c` example in this guide is one physical line; do not insert a PowerShell continuation backtick between `-c` and its quoted program.
Stop if the existing gate fails or the working tree contains unexplained changes. Step 39 should create a reviewable delta from a known baseline. Record unrelated work rather than sweeping it into this milestone.
## Define the Step 39 boundary
The deliverable is **hashed credential and session boundary**. Write down its caller, inputs, outputs, error semantics, resource ownership, and observable result before selecting a library. A tool name is not an architecture. The boundary should remain testable when Windows paths contain spaces, the working directory changes, the network is unavailable, or an optional dependency is missing.
Create the smallest module or configuration file that owns Authentication foundations. Keep domain policy separate from adapters that touch the filesystem, process environment, network, database, GUI, operating system, or external service. Pure policy can be tested quickly; adapters need explicit integration tests and cleanup.
Do not hard-code `C:\Users\Danny Li`, a drive letter, a personal checkout, or a `.venv` executable. Derive project resources with `pathlib`, accept deployment locations through validated configuration, and keep user-specific state outside source control.
## Inspect before adding dependencies
Search the project for an existing owner:
```powershell
Get-ChildItem -Recurse -File | Select-String -SimpleMatch "Authentication foundations"
git ls-files
```
If the repository already has a framework, configuration section, adapter, test helper, or operational policy for this subject, extend that source of truth. Do not create parallel logging systems, HTTP clients, database sessions, configuration loaders, test runners, packaging metadata, or release scripts.
Prefer the standard library when it satisfies the contract. When a third-party distribution is justified, verify its official project identity, supported Python versions, license, maintenance posture, release notes, and transitive dependencies. Install it only through the selected interpreter and add it to the project's established dependency source.
```powershell
python -m pip check
python -m pip freeze
```
`pip freeze` is evidence of the current environment, not permission to replace a reviewed lock or dependency declaration. Never copy package versions blindly from this article; resolve according to project policy and test the resulting set on every supported Python version.
## Implement one vertical slice
Build a thin end-to-end slice: accept one valid input, execute the Authentication foundations policy, return or persist the intended output, and expose one useful diagnostic. Keep side effects behind a narrow function/class so tests can substitute a controlled adapter.
Use explicit names and types. Validate at trust boundaries rather than deep inside business logic. Return stable domain results or raise a small documented exception family; do not leak raw library exceptions through every layer. Preserve causal context with exception chaining when translation is necessary.
The primary Step 39 exercise command is:
```powershell
python -m pytest tests\test_auth.py
```
Run it from the project root through the verified interpreter/tool owner. If it is a diagnostic command, capture only non-sensitive facts. If it starts a service or GUI, use a development-only binding and stop it cleanly after the smoke check. If it invokes a test, make the test independent of live production services.
## Model inputs and outputs explicitly
Document required versus optional fields, accepted ranges, encoding, path rules, time-zone expectations, and maximum sizes. Reject ambiguous or malformed data with an actionable message. Defaults should be safe, visible, and stable; an absent critical setting must not silently select a dangerous behavior.
Machine-readable output needs a versioned schema or compatibility policy. Human-readable output should separate normal results on stdout from diagnostics on stderr and use meaningful exit codes. Do not parse localized display text as an internal interface.
For files, write to a temporary sibling and atomically replace where the filesystem supports it. For databases, define transaction ownership. For network work, set connect/read/total time budgets. For processes, pass argument lists rather than shell-built strings. For concurrency, define cancellation and shutdown before starting workers.
## Test behavior and failure
Add tests beside the established suite. Cover one normal example, a meaningful boundary, malformed input, an unavailable dependency, and cleanup after an injected failure. Assert public results and durable side effects rather than private call order.
Use temporary directories and temporary databases. Use fakes at remote boundaries for fast deterministic tests, then add a smaller integration test that proves the real adapter contract. Never point automated tests at a shared production account, personal directory, mapped drive, or mutable external resource.
Run focused tests first, then the full gate:
```powershell
python -m pytest -q
python .\quality_gate.py
```
A passing happy path is insufficient. Deliberately violate one invariant and confirm the test fails for the intended reason; restore it and rerun. This negative proof catches skipped tests, incorrect discovery, swallowed exit codes, and assertions that never execute.
## Windows-specific qualification
Exercise paths containing spaces and non-ASCII characters. Do not assume a case-sensitive filesystem, POSIX separators, executable permission bits, `fork`, Bash syntax, or a visible interactive desktop. Services and scheduled tasks often have different profiles, environment variables, network-drive mappings, certificate stores, and working directories than the developer terminal.
Open files with explicit text encoding and appropriate newline behavior. Close handles deterministically so Windows can rename or delete temporary files. Bound retry behavior around transient sharing violations; never turn an access-denied or persistent lock into an infinite loop.
If the feature crosses PowerShell, `cmd.exe`, WSL, COM, Task Scheduler, a Windows service, or a container boundary, document which parser and identity owns every argument. Test exit-code propagation. Avoid `shell=True` and string-built commands when an argument array or direct API exists.
## Security and privacy review
Apply least privilege to files, tokens, workflow permissions, network listeners, database roles, and service accounts. Keep secrets out of command lines, URLs, repository files, exceptions, screenshots, test fixtures, and logs. Redact by field policy rather than after arbitrary strings have already been emitted.
Treat external files, archives, JSON, CSV, HTTP responses, package artifacts, environment variables, registry values, queue messages, and user input as untrusted. Validate size before allocation, normalize only after defining semantics, and reject traversal or unexpected destinations. Never disable TLS verification, ACLs, authentication, or safety checks merely to make a tutorial command pass.
The Step 39 threat review must directly address **inventing cryptography or storing plaintext credentials**. Record the chosen control and a test or operational check that proves it. If the control needs new credentials, infrastructure, administrator rights, or external coordination, stop and obtain that authority rather than hiding the dependency.
## CI parity
Commit the implementation, configuration, tests, and dependency changes—never the `.venv` or tool caches. Step 7 should rebuild them on clean Windows runners and invoke the same `quality_gate.py` used locally.
```powershell
git status --short
git diff
python .\quality_gate.py
```
Do not add a second CI-only policy that disagrees with local commands. A cache hit may improve speed but must not provide undeclared correctness. The job must still install declarations, run `pip check`, and execute the gate.
When the capability requires slow integration or end-to-end tests, mark and schedule them deliberately while keeping a fast pull-request signal. A required check must not silently skip the only test that proves this milestone.
## Observability and operations
Define what an operator can observe without attaching a debugger: success count, bounded latency, failure category, dependency health, queue depth, last completed operation, or another signal appropriate to Authentication foundations. Use stable structured fields and correlation identifiers where requests cross components.
Do not log entire payloads by default. Bound log size, metric cardinality, artifact retention, and diagnostic collection. Health checks should distinguish process liveness from readiness to serve; a running process with an unavailable required dependency is not necessarily ready.
Write the recovery action beside the signal. An alert without an owner or safe response is noise. Test alert conditions and diagnostic redaction just like application behavior.
## Rollout and rollback
Introduce the capability behind a narrow configuration switch or reversible integration point when risk justifies it. Establish the baseline, deploy to the smallest representative scope, observe the acceptance signal, and expand only after the result is understood.
Rollback must name the prior artifact/configuration, compatibility constraints, data consequences, and verification command. Code rollback may not reverse a schema migration, emitted message, encrypted value, external side effect, or overwritten file. Design forward repair when reversal is unsafe.
Record who owns the feature after merge, how dependencies are updated, what evidence is retained, and when the policy is reviewed. Setup is not complete when a command runs once; it is complete when another person can reproduce, diagnose, and safely retire it.
## Troubleshooting without destructive shortcuts
**The command is not found.** Recheck `sys.executable`, use `python -m ...`, and verify the dependency declaration. Do not install globally or use `--user` to mask a project problem.
**It works only from VS Code.** Compare selected interpreter, working directory, environment, launch configuration, and unsaved files. The project command and CI gate remain authoritative.
**It works only on the developer machine.** Search for undeclared packages, absolute paths, user-site imports, cached state, credentials, mapped drives, locale assumptions, and interactive prompts. Reproduce on the clean Windows matrix.
**Tests hang.** Add timeouts at the real blocking boundary; inspect threads, child processes, sockets, UI loops, locks, and teardown. Do not add arbitrary sleeps as synchronization.
**Access is denied.** Identify the exact path/object and effective identity, inspect ownership/ACLs, and grant the minimum required access. Do not run the entire application as Administrator.
**A test is flaky.** Capture seed, timing, ordering, concurrency, locale, and external-state evidence. Make the dependency controllable instead of rerunning until green.
**CI differs from local.** Compare recorded Python version, dependency resolution, configuration sources, path casing, line endings, and collected tests. Preserve the failing log before changing state.
## What not to do in Step 39
- Do not bypass Steps 1–7 interpreter, dependency, quality, or CI evidence.
- Do not hard-code personal Windows paths, tokens, hosts, or credentials.
- Do not create a duplicate framework or configuration source.
- Do not rely on current working directory, global packages, or user-site imports.
- Do not make live production services part of unit tests.
- Do not swallow exceptions or convert every failure to a successful exit.
- Do not disable validation, TLS, authentication, ACLs, or safety checks.
- Do not commit virtual environments, caches, generated secrets, or private data.
- Do not apply automatic fixes without reviewing the source diff.
- Do not call the milestone complete until a deliberate failure is detected.
| Step 39 acceptance | Pass condition | Stop condition |
|---|---|---|
| project baseline | interpreter, pip, and quality gate agree | unresolved prior failure |
| deliverable | hashed credential and session boundary exists in reviewed source | machine-only hidden state |
| normal behavior | success, denial, expiry, rotation, and rate limits are tested | ambiguous or unobserved result |
| invalid input | fails early with actionable error | silent coercion or corruption |
| injected failure | test and process return nonzero | swallowed error or skipped test |
| Windows qualification | spaces, Unicode, cleanup, identity pass | user-specific assumption |
| security | control addresses inventing cryptography or storing plaintext credentials | unsafe workaround required |
| clean CI | supported Windows matrix rebuilds and passes | cache/global dependency |
| operations | signal, owner, and recovery are documented | no safe diagnosis/rollback |
## Step 39 completion gate
Step 39 is complete only when the deliverable is committed with tests and declarations; normal, boundary, and injected-failure cases are proven; Windows-specific behavior is qualified; the named risk has a tested control; the full local quality gate passes; clean Windows CI passes without hidden state; and another operator can diagnose and reverse or safely repair the change.
Run final local evidence:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -m pytest tests\test_auth.py
python .\quality_gate.py
git status --short
```
Review output before publishing it. Remove personal paths, tokens, internal hostnames, private index details, customer data, and unnecessary payloads from logs or screenshots.
Step 40 continues with **TLS and certificates**. Carry forward the same interpreter evidence, source-control review, and non-mutating gate.
**Windows Python Setup Step 39 succeeds when success, denial, expiry, rotation, and rate limits are tested, the failure path is deliberately proven, clean Windows CI reproduces the result, and the operational owner can observe and recover it without relying on the developer's machine.**
python vscode windows step 4, vscode python setup windows, select interpreter vscode, vscode use .venv windows, python debugger vscode, verify vscode interpreter, windows python editor setup, python vscode beginner
**Windows Python Setup Step 4 is to make Visual Studio Code consume the verified project `.venv`, then prove that editor analysis, the integrated terminal, Run Python File, and the debugger all resolve the same interpreter.** An editor should not silently create a second environment, install packages globally, or hide a mismatch behind a green Run button.
This page uses Visual Studio Code with Microsoft’s Python tooling because it provides interpreter discovery, IntelliSense, running, debugging, testing integration, and environment-aware terminals on Windows. If your project or organization standardizes on another editor, keep the same acceptance principle: every execution surface must report the `.venv` established in Step 2 and populated in Step 3.
| Surface | Expected owner | Proof |
|---|---|---|
| VS Code workspace | project root folder | Explorer shows project files |
| selected environment | workspace `.venv` | status/environment control |
| integrated terminal | local interpreter | `sys.executable` is local |
| Run Python File | selected interpreter | script prints local path |
| debugger | selected interpreter | debug console reports local path |
| language analysis | selected environment | installed import resolves |
| shared configuration | relative workspace files | no user-specific path |
## Step 4 prerequisites
In a normal PowerShell window, return to the Step 2/3 project:
```powershell
Set-Location "$HOME\Projects\hello-python"
.\.venv\Scripts\Activate.ps1
```
Verify the environment with the exact single-line command:
```powershell
python -c "import sys; print(sys.executable)"
python -m pip check
python -c "import requests; print(requests.__file__)"
```
The interpreter and imported `requests` module must be inside `.venv`, and `pip check` must pass. If not, return to Step 2 or Step 3. VS Code configuration cannot repair a wrong or inconsistent environment.
## Install Visual Studio Code from a trusted source
Download the Windows **User Setup** from the [official VS Code website](https://code.visualstudio.com/) or use your organization’s approved software catalog. The user installer is the standard choice for a personal Windows account because it does not require a machine-wide installation.
During installation, review options rather than clicking through blindly. Adding the `code` command to PATH is convenient but not required; context-menu entries are optional. File associations do not decide which Python interpreter runs inside the editor.
On a managed computer, use the approved version and extension marketplace policy. Do not download a repackaged editor, disable application control, or install extensions from unknown publishers.
After installation, close and reopen PowerShell if you intend to use the `code` command. Verify:
```powershell
code --version
```
If `code` is not recognized, open VS Code from the Start menu and use **File → Open Folder**. Do not reinstall Python to fix a missing editor command.
## Install the Microsoft Python extension
Open VS Code, select **Extensions** or press `Ctrl+Shift+X`, search for **Python**, and select the extension published by **Microsoft**. Confirm the publisher and extension identifier before installing. The core identifier is:
```text
ms-python.python
```
The current Python environment-management experience may also involve Microsoft’s Python Environments extension alongside the Python extension. Let VS Code install official dependencies/companions required by the extension; do not substitute a similarly named third-party extension.
If organization policy permits command-line extension installation, the equivalent is:
```powershell
code --install-extension ms-python.python
```
Restart or reload VS Code if prompted. An extension adds editor integration; it does not install the Python runtime or recreate `.venv` unless you explicitly ask it to create an environment.
## Open the project folder, not only the file
From the activated project PowerShell window, run:
```powershell
code .
```
The dot means the current project directory. Alternatively, in VS Code use **File → Open Folder** and choose `hello-python`.
Opening only `hello.py` gives VS Code less workspace context: it may not discover `.venv`, requirements files, `.vscode` settings, debug configurations, or project-relative paths correctly. The Explorer should show at least the project files and `.venv` folder.
The window title and Explorer root should identify `hello-python`. If VS Code opened the parent `Projects` directory, close it and open the actual project root; environment discovery over a broad folder can find unrelated environments.
## Evaluate Workspace Trust deliberately
VS Code may ask whether you trust the folder’s authors. Trust allows tasks, debugging, workspace settings, and extensions to execute code. Trust a project you created yourself. For cloned or downloaded code, review the source, task files, debug configurations, extension recommendations, and setup scripts before granting trust.
Restricted Mode is appropriate while inspecting untrusted content. Do not grant trust merely to remove a banner. A Python package, editor extension, task, or debug configuration can execute with your user permissions.
## Select the existing `.venv`
Open a Python file. In the VS Code status bar, select the displayed Python environment/version, or open the Command Palette with `Ctrl+Shift+P` and run:
```text
Python: Select Interpreter
```
Choose the interpreter whose path ends with:
```text
.venv\Scripts\python.exe
```
Do not choose the global Python from Step 1, `.venv-check` from Step 3, a WSL interpreter, or an environment belonging to another project.
The current VS Code Python environment tooling normally discovers workspace-local `.venv` directories automatically and prioritizes them over global interpreters. Manual selection is still valuable because it creates an explicit, auditable workspace choice.
## If `.venv` is missing from the interpreter list
First prove the environment exists outside VS Code:
```powershell
Test-Path .\.venv\pyvenv.cfg
Test-Path .\.venv\Scripts\python.exe
```
Then use the Command Palette and run:
```text
Python Environments: Refresh All Environment Managers
```
If discovery remains stale, reload the VS Code window. Confirm the actual project root is open. The current default workspace search includes `.venv` folders, so a basic project should not need a custom absolute path.
As a final manual option, use **Python: Select Interpreter**, choose the option to enter/find an interpreter path, and select the project’s `.venv\Scripts\python.exe`. Do not paste a machine-specific path into a shared repository setting.
If the environment appears “broken,” recreate it through Step 2 rather than editing `pyvenv.cfg` or copying executables.
## Understand what interpreter selection controls
The selected environment is used by the Python tooling for:
- running Python files;
- debugging Python configurations unless explicitly overridden;
- language services and import analysis;
- test discovery/execution when configured;
- environment-aware integrated terminals;
- environment and package-management UI.
Selection is workspace context, not a permanent rewrite of Windows PATH. Another VS Code folder can select another environment, and an external PowerShell window keeps its own activation state.
## Create a new integrated terminal
Close terminals that were open before interpreter selection. Use **Terminal → New Terminal** or ``Ctrl+` ``. The Python tooling normally activates the selected environment in a new terminal.
Run:
```powershell
python --version
python -c "import sys; print(sys.executable)"
python -m pip --version
```
Both paths must point inside the project `.venv`. If the prompt shows `(.venv)` but the path is global, trust `sys.executable`, not the prompt.
Terminal activation settings and behavior can change. The current Python Environments tooling supports automatic activation modes; after changing an activation setting, create a new terminal because existing terminals keep their current process environment.
If PowerShell policy blocks `Activate.ps1`, the selected interpreter can still run files and debug. For terminal commands, use the explicit environment interpreter or follow the policy-respecting Step 2 guidance. Do not set execution policy to `Unrestricted` for the editor.
## Build a Step 4 probe script
Create `step4_probe.py` in the project root:
```python
from importlib.metadata import version
from pathlib import Path
import sys
def environment_report() -> dict[str, str]:
return {
"executable": sys.executable,
"prefix": sys.prefix,
"cwd": str(Path.cwd()),
"requests": version("requests"),
}
if __name__ == "__main__":
for key, value in environment_report().items():
print(f"{key}: {value}")
```
This reports interpreter identity, environment prefix, working directory, and installed distribution metadata. It makes mismatches visible without making a network request.
Save the file. The editor should recognize Python syntax, offer completion, and avoid an unresolved-import warning for `requests`. Language analysis is useful evidence, but runtime checks remain authoritative.
## Run the file in the integrated terminal
With `step4_probe.py` active, select the top-right **Run Python File in Terminal** button, or use the Command Palette command with the same name.
Inspect the command VS Code sends and the output. `executable` and `prefix` should point inside `.venv`; `cwd` should be the project root; and the `requests` distribution version should print.
Run the same file manually in the integrated terminal:
```powershell
python .\step4_probe.py
```
The two execution paths should agree. If Run Python File succeeds but the manual command uses global Python, the terminal was created before selection or auto-activation is off. Recreate the terminal and reverify.
## Do not use “Run Code” as the acceptance test
Some third-party extensions add a generic **Run Code** button. It may launch a configured global interpreter or a nonterminal output channel that does not follow the selected Python environment.
For Step 4, use Microsoft’s **Run Python File in Terminal** or an explicit `.venv` command. Remove or disable overlapping runner extensions if they make execution ownership ambiguous.
## Start the debugger without a custom configuration
Open `step4_probe.py`. Place a breakpoint on the `return` line inside `environment_report` by clicking the gutter. Press `F5` or choose **Run → Start Debugging**. If prompted, select **Python Debugger** and **Python File**.
VS Code should pause at the breakpoint. Inspect:
- the Variables panel for local/global values;
- the Call Stack for `environment_report`;
- the Debug Console for expression evaluation;
- the integrated terminal/output for the final report.
In the Debug Console, evaluate:
```python
sys.executable
```
It must identify the same `.venv` interpreter. Continue with `F5` and confirm the printed report.
## Add a shareable `launch.json`
For a stable current-file debug entry, create `.vscode\launch.json` through **Run and Debug → create a launch.json file**, choose **Python Debugger**, then use:
```json
{
"version": "0.2.0",
"configurations": [
{
"name": "Step 4: Current Python File",
"type": "debugpy",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"justMyCode": true
}
]
}
```
The current official debugger type is `debugpy`. Because this configuration does not specify a `python` property, the debugger uses the selected environment. That is intentional: it avoids a user-specific absolute path and survives recreation of `.venv`.
Select **Step 4: Current Python File** in Run and Debug and repeat the breakpoint test. Commit `launch.json` only if it is useful and safe for collaborators.
## Avoid hard-coded interpreter paths
Do not put a path containing your Windows username into `launch.json` or shared settings. A teammate, CI runner, or future machine will not have it. Prefer workspace environment selection and relative program paths.
The debugger supports a `python` property when a configuration intentionally needs a different interpreter. Step 4 does not: its purpose is to prove that running and debugging consume the same selected `.venv`.
If you must override an interpreter for a specialized debug target, document why, use a portable mechanism where possible, and add a separate verification. An override can make the debugger disagree with the terminal and language service.
## Inspect workspace settings before committing them
Open `.vscode\settings.json` if it exists. Modern Python Environments project assignment can store portable environment-manager information rather than a machine-specific interpreter path. Avoid adding legacy or absolute settings copied from old tutorials without confirming their current meaning.
Useful shared editor configuration should be:
- relative to the workspace;
- required by the project rather than personal taste;
- documented;
- free of credentials and local usernames;
- compatible with the team’s supported platforms;
- reviewed because workspace settings can influence execution.
User preferences such as theme, font size, and personal keyboard shortcuts generally do not belong in the repository.
## Extension recommendations are code-supply-chain decisions
A project may contain `.vscode\extensions.json` recommendations. Review each identifier and publisher before installation. Recommendations are not mandatory proof of trust.
For a basic Python workspace, Microsoft’s Python extension is the central requirement. Pylance, Python Environments, and Python Debugger may appear as Microsoft companions/dependencies. Install formatters, linters, test adapters, notebook support, and AI tools only when the project chooses them.
Too many overlapping extensions can create duplicate Run buttons, competing formatters, different environment selectors, and confusing diagnostics. Add one capability at a time and verify its owner.
## Terminal, Run, Debug, and analysis are separate surfaces
Do not infer that one passing surface proves all others:
- The integrated terminal inherits shell activation state.
- Run Python File uses the selected interpreter and editor integration.
- Debug uses the selected interpreter unless `launch.json` overrides it.
- Language analysis resolves imports using the selected environment and its own process/cache.
- A notebook uses a separately selected kernel and is outside this Step 4 acceptance test.
Record `sys.executable` from terminal, Run, and Debug. If analysis still shows stale import errors after those agree, reload the window and inspect the selected environment rather than reinstalling the package.
## WSL and Windows interpreters must not be mixed
A local Windows VS Code window using `.venv\Scripts\python.exe` is different from a VS Code window connected to WSL, where paths and environments are Linux-based. The lower-left remote indicator identifies remote context.
If the project is meant for WSL, open it through the WSL extension, create a Linux virtual environment inside WSL, and select that Linux interpreter. Do not select a Windows `.venv` for a WSL workspace or vice versa.
## Verify source-control state
Run in the integrated terminal:
```powershell
git status
```
Expected project artifacts may include:
- `step4_probe.py`;
- `.vscode\launch.json` if intentionally shared;
- existing dependency declarations;
- `.gitignore` updates.
The `.venv` and `.venv-check` directories must remain ignored. Review every `.vscode` file before committing because tasks and debug configurations can execute commands.
## Common failures and targeted fixes
**The status bar shows global Python.** Run **Python: Select Interpreter** and choose the workspace `.venv`. Then create a new terminal.
**`.venv` does not appear.** Confirm the project root and environment files, refresh environment managers, reload the window, or select the interpreter file manually.
**The terminal uses global Python after selection.** Close the existing terminal and create a new one. Check auto-activation behavior and PowerShell policy. Use `sys.executable` as evidence.
**Run Python File uses the right interpreter but Debug does not.** Inspect `launch.json` for a `python` override or an unrelated debug configuration. Use `type: debugpy` and the selected environment.
**The debugger will not stop at a breakpoint.** Confirm the active debug configuration, save the file, place the breakpoint on executable code, and ensure `program` points to the intended file.
**`requests` runs but the editor says import cannot be resolved.** Confirm the selected interpreter, wait for analysis refresh, reload the window, and inspect `requests.__file__`. Do not reinstall globally.
**The editor shows several Python Run buttons.** Identify their extension owners. Disable overlapping generic runner extensions and retain a single documented Python path.
**VS Code created `.venv-1`.** Do not switch automatically. Step 2 already created `.venv`; delete only after identifying ownership and preserving dependencies. Select the intended environment.
**Workspace Trust blocks debugging.** Review the project before trusting it. Do not bypass Restricted Mode for unknown code.
**A setting works only on your PC.** Look for absolute paths, usernames, drive letters, shell-specific assumptions, and unreviewed extensions. Replace them with portable workspace behavior.
## What not to do in Step 4
- Do not let the editor silently create a second environment.
- Do not select global Python because it appears first.
- Do not trust prompt decoration without checking `sys.executable`.
- Do not hard-code a personal interpreter path in shared settings.
- Do not add a debugger `python` override without a specific reason.
- Do not install overlapping runner/debugger extensions casually.
- Do not grant Workspace Trust to unreviewed code.
- Do not commit secrets in `.env`, settings, tasks, or debug configuration.
- Do not mix a Windows interpreter with a WSL workspace.
- Do not assume notebook kernel selection matches the Python interpreter selection.
- Do not reinstall packages globally to silence editor diagnostics.
| Step 4 gate | Pass condition | If it fails |
|---|---|---|
| trusted installation | official/approved VS Code | reinstall from trusted source |
| extension owner | Microsoft Python tooling | remove ambiguous extension |
| workspace root | actual project folder | reopen correct folder |
| environment selection | project `.venv` | select or refresh discovery |
| integrated terminal | local executable | create a new terminal |
| Run Python File | local probe output | inspect selected interpreter |
| debugger | same local executable | repair `launch.json` |
| shared configuration | portable and reviewed | remove personal paths/secrets |
## Step 4 completion gate
Step 4 is complete only when:
1. VS Code and the Microsoft Python extension came from trusted sources.
2. The actual project root is open and trusted only after review.
3. The selected environment is the existing workspace `.venv`.
4. A newly created integrated terminal reports the `.venv` interpreter.
5. Run Python File executes `step4_probe.py` through the same interpreter.
6. The Python debugger stops at a breakpoint and reports the same interpreter.
7. Language analysis resolves the Step 3 dependency from that environment.
8. Shared `.vscode` files contain no personal absolute paths or secrets.
Capture the terminal evidence with:
```powershell
python -c "import sys; print(sys.executable)"
python -c "import requests; print(requests.__file__)"
python .\step4_probe.py
```
Capture debugger evidence by evaluating `sys.executable` at the breakpoint. The terminal, Run output, and Debug Console paths should resolve to the same `.venv` even if their printed path formatting differs in slash direction or case.
The next step can add a test runner, formatter, linter/type checker, and repeatable quality commands. Those tools should be declared as project development dependencies and executed through this same selected environment rather than installed as unexplained global editor utilities.
**Windows Python Setup Step 4 succeeds when VS Code is a transparent client of the existing `.venv`: terminal, Run, Debug, and analysis all agree, and shared configuration remains portable and reviewable.**