<?xml version="1.0" encoding="UTF-8"?>
<rss  xmlns:atom="http://www.w3.org/2005/Atom" 
      xmlns:media="http://search.yahoo.com/mrss/" 
      xmlns:content="http://purl.org/rss/1.0/modules/content/" 
      xmlns:dc="http://purl.org/dc/elements/1.1/" 
      version="2.0">
<channel>
<title>Vectoring AI</title>
<link>https://vectoringai.com/pages/swe-interview.html</link>
<atom:link href="https://vectoringai.com/pages/swe-interview.xml" rel="self" type="application/rss+xml"/>
<description>Software engineering interview questions covering fundamentals, advanced internals, design patterns, best practices, and production code structure.</description>
<generator>quarto-1.9.36</generator>
<lastBuildDate>Thu, 21 May 2026 00:00:00 GMT</lastBuildDate>
<item>
  <title>Python SWE Interview QA - 4</title>
  <dc:creator>Vectoring AI</dc:creator>
  <link>https://vectoringai.com/posts/swe-interview/Python-SWE-Interview-QA-4.html</link>
  <description><![CDATA[ 




<section id="introduction" class="level2">
<h2 class="anchored" data-anchor-id="introduction">Introduction</h2>
<p>This is <strong>Part 4</strong> of our Python SWE Interview QA series, focused on <strong>building production REST APIs</strong> — covering API design, concurrency under load, latency optimization, and security hardening. These are the questions that separate backend engineers who ship to production from those who only build prototypes.</p>
<blockquote class="blockquote">
<p>For foundational Python topics, see <a href="../../posts/swe-interview/Python-SWE-Interview-QA-1.html">Python SWE Interview QA - 1</a>. For advanced internals, see <a href="../../posts/swe-interview/Python-SWE-Interview-QA-2.html">Part 2</a>. For design patterns and code structure, see <a href="../../posts/swe-interview/Python-SWE-Interview-QA-3.html">Part 3</a>.</p>
</blockquote>
<hr>
</section>
<section id="q1-how-do-you-design-a-restful-api-in-python-and-what-are-the-best-practices" class="level2">
<h2 class="anchored" data-anchor-id="q1-how-do-you-design-a-restful-api-in-python-and-what-are-the-best-practices">Q1: How do you design a RESTful API in Python and what are the best practices?</h2>
<p><strong>Answer:</strong></p>
<p>A well-designed REST API follows consistent conventions for resources, HTTP methods, status codes, and response formats — making it predictable and self-documenting.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    CLIENT["Client (Frontend / Mobile)"]
    CLIENT --&gt;|"GET /users/123"| API["REST API (FastAPI / Flask)"]
    API --&gt;|"200 OK + JSON body"| CLIENT

    API --&gt; AUTH["Authentication&lt;br/&gt;JWT / OAuth2"]
    API --&gt; VALID["Validation&lt;br/&gt;Pydantic / Marshmallow"]
    API --&gt; SERVICE["Service Layer&lt;br/&gt;Business Logic"]
    SERVICE --&gt; DB["Database"]
    SERVICE --&gt; CACHE["Cache (Redis)"]

    style API fill:#56cc9d,stroke:#333,color:#fff
    style AUTH fill:#ff7851,stroke:#333,color:#fff
    style SERVICE fill:#6cc3d5,stroke:#333,color:#fff
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="restful-url-design" class="level3">
<h3 class="anchored" data-anchor-id="restful-url-design">RESTful URL Design</h3>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Action</th>
<th>HTTP Method</th>
<th>URL</th>
<th>Status Code</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>List users</td>
<td><code>GET</code></td>
<td><code>/api/v1/users</code></td>
<td>200</td>
</tr>
<tr class="even">
<td>Get one user</td>
<td><code>GET</code></td>
<td><code>/api/v1/users/{id}</code></td>
<td>200 / 404</td>
</tr>
<tr class="odd">
<td>Create user</td>
<td><code>POST</code></td>
<td><code>/api/v1/users</code></td>
<td>201</td>
</tr>
<tr class="even">
<td>Update user (full)</td>
<td><code>PUT</code></td>
<td><code>/api/v1/users/{id}</code></td>
<td>200 / 404</td>
</tr>
<tr class="odd">
<td>Update user (partial)</td>
<td><code>PATCH</code></td>
<td><code>/api/v1/users/{id}</code></td>
<td>200 / 404</td>
</tr>
<tr class="even">
<td>Delete user</td>
<td><code>DELETE</code></td>
<td><code>/api/v1/users/{id}</code></td>
<td>204 / 404</td>
</tr>
<tr class="odd">
<td>User’s orders</td>
<td><code>GET</code></td>
<td><code>/api/v1/users/{id}/orders</code></td>
<td>200</td>
</tr>
</tbody>
</table>
</section>
<section id="fastapi-implementation" class="level3">
<h3 class="anchored" data-anchor-id="fastapi-implementation">FastAPI Implementation</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> fastapi <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> FastAPI, HTTPException, Depends, Query, status</span>
<span id="cb1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> pydantic <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> BaseModel, EmailStr, Field</span>
<span id="cb1-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> datetime <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> datetime</span>
<span id="cb1-4"></span>
<span id="cb1-5">app <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> FastAPI(title<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"User Service"</span>, version<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1.0.0"</span>)</span>
<span id="cb1-6"></span>
<span id="cb1-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Request/Response models (validation + documentation)</span></span>
<span id="cb1-8"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> UserCreate(BaseModel):</span>
<span id="cb1-9">    name: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Field(..., min_length<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, max_length<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>)</span>
<span id="cb1-10">    email: EmailStr</span>
<span id="cb1-11">    role: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"user"</span></span>
<span id="cb1-12"></span>
<span id="cb1-13"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> UserResponse(BaseModel):</span>
<span id="cb1-14">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">id</span>: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span></span>
<span id="cb1-15">    name: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span></span>
<span id="cb1-16">    email: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span></span>
<span id="cb1-17">    role: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span></span>
<span id="cb1-18">    created_at: datetime</span>
<span id="cb1-19"></span>
<span id="cb1-20">    model_config <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"from_attributes"</span>: <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>}</span>
<span id="cb1-21"></span>
<span id="cb1-22"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> PaginatedResponse(BaseModel):</span>
<span id="cb1-23">    items: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>[UserResponse]</span>
<span id="cb1-24">    total: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span></span>
<span id="cb1-25">    page: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span></span>
<span id="cb1-26">    page_size: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span></span>
<span id="cb1-27"></span>
<span id="cb1-28"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Endpoints</span></span>
<span id="cb1-29"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@app.get</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/api/v1/users"</span>, response_model<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>PaginatedResponse)</span>
<span id="cb1-30"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> list_users(</span>
<span id="cb1-31">    page: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Query(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, ge<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>),</span>
<span id="cb1-32">    page_size: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Query(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, ge<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, le<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>),</span>
<span id="cb1-33">    role: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>,</span>
<span id="cb1-34">):</span>
<span id="cb1-35">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""List users with pagination and optional filtering."""</span></span>
<span id="cb1-36">    users, total <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> user_service.list_users(</span>
<span id="cb1-37">        page<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>page, page_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>page_size, role<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>role</span>
<span id="cb1-38">    )</span>
<span id="cb1-39">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> PaginatedResponse(</span>
<span id="cb1-40">        items<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>users, total<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>total, page<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>page, page_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>page_size</span>
<span id="cb1-41">    )</span>
<span id="cb1-42"></span>
<span id="cb1-43"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@app.post</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/api/v1/users"</span>, response_model<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>UserResponse, status_code<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>status.HTTP_201_CREATED)</span>
<span id="cb1-44"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> create_user(user_data: UserCreate):</span>
<span id="cb1-45">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Create a new user."""</span></span>
<span id="cb1-46">    user <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> user_service.create_user(user_data)</span>
<span id="cb1-47">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> user</span>
<span id="cb1-48"></span>
<span id="cb1-49"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@app.get</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/api/v1/users/</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{user_id}</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>, response_model<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>UserResponse)</span>
<span id="cb1-50"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_user(user_id: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>):</span>
<span id="cb1-51">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Get a single user by ID."""</span></span>
<span id="cb1-52">    user <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> user_service.get_by_id(user_id)</span>
<span id="cb1-53">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> user:</span>
<span id="cb1-54">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> HTTPException(status_code<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">404</span>, detail<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"User not found"</span>)</span>
<span id="cb1-55">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> user</span></code></pre></div></div>
</section>
<section id="api-design-best-practices" class="level3">
<h3 class="anchored" data-anchor-id="api-design-best-practices">API Design Best Practices</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 66%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Practice</th>
<th>Why</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Use nouns for resources (<code>/users</code>), not verbs (<code>/getUsers</code>)</td>
<td>HTTP method already conveys the action</td>
</tr>
<tr class="even">
<td>Version your API (<code>/api/v1/...</code>)</td>
<td>Non-breaking evolution</td>
</tr>
<tr class="odd">
<td>Use proper HTTP status codes</td>
<td>Clients can handle responses generically</td>
</tr>
<tr class="even">
<td>Paginate list endpoints</td>
<td>Prevent unbounded responses</td>
</tr>
<tr class="odd">
<td>Use Pydantic for request/response models</td>
<td>Auto-validation + OpenAPI docs</td>
</tr>
<tr class="even">
<td>Return consistent error format</td>
<td><code>{"detail": "...", "code": "..."}</code></td>
</tr>
<tr class="odd">
<td>Use plural nouns (<code>/users</code>, not <code>/user</code>)</td>
<td>Consistent collection semantics</td>
</tr>
</tbody>
</table>
<hr>
</section>
</section>
<section id="q2-how-do-you-handle-concurrency-in-a-production-python-api" class="level2">
<h2 class="anchored" data-anchor-id="q2-how-do-you-handle-concurrency-in-a-production-python-api">Q2: How do you handle concurrency in a production Python API?</h2>
<p><strong>Answer:</strong></p>
<p>Production APIs must handle thousands of concurrent requests. Python achieves this through a combination of <strong>async I/O</strong>, <strong>worker processes</strong>, and <strong>connection pooling</strong>.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    LB["Load Balancer (Nginx)"]
    LB --&gt; W1["Uvicorn Worker 1&lt;br/&gt;(async event loop)"]
    LB --&gt; W2["Uvicorn Worker 2&lt;br/&gt;(async event loop)"]
    LB --&gt; W3["Uvicorn Worker 3&lt;br/&gt;(async event loop)"]
    LB --&gt; W4["Uvicorn Worker 4&lt;br/&gt;(async event loop)"]

    W1 --&gt; POOL["Connection Pool&lt;br/&gt;(asyncpg / aioredis)"]
    W2 --&gt; POOL
    W3 --&gt; POOL
    W4 --&gt; POOL

    POOL --&gt; DB["PostgreSQL"]
    POOL --&gt; REDIS["Redis"]

    style LB fill:#56cc9d,stroke:#333,color:#fff
    style POOL fill:#ffce67,stroke:#333
    style DB fill:#6cc3d5,stroke:#333,color:#fff
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="production-deployment-architecture" class="level3">
<h3 class="anchored" data-anchor-id="production-deployment-architecture">Production Deployment Architecture</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># gunicorn.conf.py — Production server configuration</span></span>
<span id="cb2-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> multiprocessing</span>
<span id="cb2-3"></span>
<span id="cb2-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Workers = 2-4 × CPU cores (for I/O-bound workloads)</span></span>
<span id="cb2-5">workers <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> multiprocessing.cpu_count() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb2-6">worker_class <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"uvicorn.workers.UvicornWorker"</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Async workers</span></span>
<span id="cb2-7">bind <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.0.0.0:8000"</span></span>
<span id="cb2-8">keepalive <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">120</span></span>
<span id="cb2-9">timeout <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span></span>
<span id="cb2-10">graceful_timeout <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span></span>
<span id="cb2-11">max_requests <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Restart worker after N requests (prevent memory leaks)</span></span>
<span id="cb2-12">max_requests_jitter <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Randomize restarts to avoid thundering herd</span></span></code></pre></div></div>
</section>
<section id="connection-pooling" class="level3">
<h3 class="anchored" data-anchor-id="connection-pooling">Connection Pooling</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> contextlib <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> asynccontextmanager</span>
<span id="cb3-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> asyncpg</span>
<span id="cb3-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> redis.asyncio <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> aioredis</span>
<span id="cb3-4"></span>
<span id="cb3-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Application lifespan — create pools once at startup</span></span>
<span id="cb3-6"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@asynccontextmanager</span></span>
<span id="cb3-7"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> lifespan(app: FastAPI):</span>
<span id="cb3-8">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Startup: create connection pools</span></span>
<span id="cb3-9">    app.state.db_pool <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> asyncpg.create_pool(</span>
<span id="cb3-10">        dsn<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>settings.database_url,</span>
<span id="cb3-11">        min_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>,          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Keep 5 connections ready</span></span>
<span id="cb3-12">        max_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>,         <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Max 20 concurrent DB connections per worker</span></span>
<span id="cb3-13">        max_inactive_connection_lifetime<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">300</span>,</span>
<span id="cb3-14">    )</span>
<span id="cb3-15">    app.state.redis <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> aioredis.from_url(</span>
<span id="cb3-16">        settings.redis_url,</span>
<span id="cb3-17">        max_connections<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>,</span>
<span id="cb3-18">    )</span>
<span id="cb3-19">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">yield</span></span>
<span id="cb3-20">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Shutdown: close pools</span></span>
<span id="cb3-21">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> app.state.db_pool.close()</span>
<span id="cb3-22">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> app.state.redis.close()</span>
<span id="cb3-23"></span>
<span id="cb3-24">app <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> FastAPI(lifespan<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>lifespan)</span>
<span id="cb3-25"></span>
<span id="cb3-26"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Usage in endpoints</span></span>
<span id="cb3-27"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_db(request: Request) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> asyncpg.Pool:</span>
<span id="cb3-28">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> request.app.state.db_pool</span>
<span id="cb3-29"></span>
<span id="cb3-30"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@app.get</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/api/v1/users/</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{user_id}</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb3-31"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_user(user_id: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>, db: asyncpg.Pool <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Depends(get_db)):</span>
<span id="cb3-32">    row <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> db.fetchrow(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"SELECT * FROM users WHERE id = $1"</span>, user_id)</span>
<span id="cb3-33">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> row:</span>
<span id="cb3-34">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> HTTPException(status_code<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">404</span>)</span>
<span id="cb3-35">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>(row)</span></code></pre></div></div>
</section>
<section id="concurrency-patterns" class="level3">
<h3 class="anchored" data-anchor-id="concurrency-patterns">Concurrency Patterns</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 32%">
<col style="width: 35%">
<col style="width: 32%">
</colgroup>
<thead>
<tr class="header">
<th>Pattern</th>
<th>Use When</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>async/await</strong></td>
<td>I/O-bound (DB, HTTP, Redis)</td>
<td><code>await db.fetch(...)</code></td>
</tr>
<tr class="even">
<td><strong>Background tasks</strong></td>
<td>Fire-and-forget (emails, logs)</td>
<td><code>BackgroundTasks</code> in FastAPI</td>
</tr>
<tr class="odd">
<td><strong>Task queues</strong></td>
<td>Heavy/long-running work</td>
<td>Celery, arq, dramatiq</td>
</tr>
<tr class="even">
<td><strong>Connection pooling</strong></td>
<td>Reuse expensive connections</td>
<td>asyncpg pool, Redis pool</td>
</tr>
<tr class="odd">
<td><strong>Worker processes</strong></td>
<td>Utilize multiple CPU cores</td>
<td>Gunicorn with N workers</td>
</tr>
</tbody>
</table>
</section>
<section id="handling-cpu-bound-work-in-an-async-api" class="level3">
<h3 class="anchored" data-anchor-id="handling-cpu-bound-work-in-an-async-api">Handling CPU-Bound Work in an Async API</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> asyncio</span>
<span id="cb4-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> concurrent.futures <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> ProcessPoolExecutor</span>
<span id="cb4-3"></span>
<span id="cb4-4">executor <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ProcessPoolExecutor(max_workers<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span>
<span id="cb4-5"></span>
<span id="cb4-6"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> cpu_intensive_task(data: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bytes</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>:</span>
<span id="cb4-7">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Runs in a separate process — doesn't block event loop."""</span></span>
<span id="cb4-8">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Heavy computation here (image processing, ML inference, etc.)</span></span>
<span id="cb4-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"result"</span>: process(data)}</span>
<span id="cb4-10"></span>
<span id="cb4-11"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@app.post</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/api/v1/process"</span>)</span>
<span id="cb4-12"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> process_data(data: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bytes</span>):</span>
<span id="cb4-13">    loop <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> asyncio.get_event_loop()</span>
<span id="cb4-14">    result <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> loop.run_in_executor(executor, cpu_intensive_task, data)</span>
<span id="cb4-15">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> result</span></code></pre></div></div>
<hr>
</section>
</section>
<section id="q3-how-do-you-implement-rate-limiting-and-throttling" class="level2">
<h2 class="anchored" data-anchor-id="q3-how-do-you-implement-rate-limiting-and-throttling">Q3: How do you implement rate limiting and throttling?</h2>
<p><strong>Answer:</strong></p>
<p><strong>Rate limiting</strong> protects your API from abuse, ensures fair usage, and prevents cascading failures under load.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    REQ["Incoming Request"]
    REQ --&gt; CHECK["Check Rate Limit&lt;br/&gt;(Redis counter)"]
    CHECK --&gt;|"Under limit"| PROCESS["Process Request"]
    CHECK --&gt;|"Over limit"| REJECT["429 Too Many Requests&lt;br/&gt;Retry-After: 60"]

    subgraph Algorithms["Rate Limiting Algorithms"]
        A1["Fixed Window&lt;br/&gt;100 req/minute"]
        A2["Sliding Window&lt;br/&gt;Smoother distribution"]
        A3["Token Bucket&lt;br/&gt;Allow bursts"]
        A4["Leaky Bucket&lt;br/&gt;Constant rate"]
    end

    style CHECK fill:#ffce67,stroke:#333
    style REJECT fill:#ff7851,stroke:#333,color:#fff
    style PROCESS fill:#56cc9d,stroke:#333,color:#fff
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="sliding-window-rate-limiter-with-redis" class="level3">
<h3 class="anchored" data-anchor-id="sliding-window-rate-limiter-with-redis">Sliding Window Rate Limiter with Redis</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> time</span>
<span id="cb5-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> fastapi <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Request, HTTPException</span>
<span id="cb5-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> redis.asyncio <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Redis</span>
<span id="cb5-4"></span>
<span id="cb5-5"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> RateLimiter:</span>
<span id="cb5-6">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Sliding window rate limiter using Redis sorted sets."""</span></span>
<span id="cb5-7"></span>
<span id="cb5-8">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, redis: Redis, requests_per_minute: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60</span>):</span>
<span id="cb5-9">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.redis <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> redis</span>
<span id="cb5-10">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.limit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> requests_per_minute</span>
<span id="cb5-11">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.window <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># seconds</span></span>
<span id="cb5-12"></span>
<span id="cb5-13">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> is_allowed(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, key: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">tuple</span>[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bool</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>]:</span>
<span id="cb5-14">        now <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> time.time()</span>
<span id="cb5-15">        window_start <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> now <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.window</span>
<span id="cb5-16">        pipe <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.redis.pipeline()</span>
<span id="cb5-17"></span>
<span id="cb5-18">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Remove expired entries</span></span>
<span id="cb5-19">        pipe.zremrangebyscore(key, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, window_start)</span>
<span id="cb5-20">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Add current request</span></span>
<span id="cb5-21">        pipe.zadd(key, {<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>(now): now})</span>
<span id="cb5-22">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Count requests in window</span></span>
<span id="cb5-23">        pipe.zcard(key)</span>
<span id="cb5-24">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Set expiry on the key</span></span>
<span id="cb5-25">        pipe.expire(key, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.window)</span>
<span id="cb5-26"></span>
<span id="cb5-27">        _, _, count, _ <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> pipe.execute()</span>
<span id="cb5-28"></span>
<span id="cb5-29">        remaining <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.limit <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> count)</span>
<span id="cb5-30">        headers <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {</span>
<span id="cb5-31">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"X-RateLimit-Limit"</span>: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.limit),</span>
<span id="cb5-32">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"X-RateLimit-Remaining"</span>: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>(remaining),</span>
<span id="cb5-33">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"X-RateLimit-Reset"</span>: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>(now <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.window)),</span>
<span id="cb5-34">        }</span>
<span id="cb5-35"></span>
<span id="cb5-36">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> count <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.limit, headers</span>
<span id="cb5-37"></span>
<span id="cb5-38"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># FastAPI middleware / dependency</span></span>
<span id="cb5-39"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> rate_limit_dependency(request: Request):</span>
<span id="cb5-40">    client_ip <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> request.client.host</span>
<span id="cb5-41">    key <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"rate_limit:</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>client_ip<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span></span>
<span id="cb5-42">    limiter <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> RateLimiter(request.app.state.redis)</span>
<span id="cb5-43">    allowed, headers <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> limiter.is_allowed(key)</span>
<span id="cb5-44"></span>
<span id="cb5-45">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> allowed:</span>
<span id="cb5-46">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> HTTPException(</span>
<span id="cb5-47">            status_code<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">429</span>,</span>
<span id="cb5-48">            detail<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Too many requests"</span>,</span>
<span id="cb5-49">            headers<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>{<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Retry-After"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"60"</span>, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>headers},</span>
<span id="cb5-50">        )</span>
<span id="cb5-51">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Attach headers to response</span></span>
<span id="cb5-52">    request.state.rate_limit_headers <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> headers</span></code></pre></div></div>
</section>
<section id="rate-limiting-strategies" class="level3">
<h3 class="anchored" data-anchor-id="rate-limiting-strategies">Rate Limiting Strategies</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Strategy</th>
<th>Approach</th>
<th>Use Case</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>Per IP</strong></td>
<td>Limit by client IP</td>
<td>Public APIs</td>
</tr>
<tr class="even">
<td><strong>Per user/API key</strong></td>
<td>Limit by authenticated identity</td>
<td>SaaS APIs</td>
</tr>
<tr class="odd">
<td><strong>Per endpoint</strong></td>
<td>Different limits for different routes</td>
<td>Heavy vs light endpoints</td>
</tr>
<tr class="even">
<td><strong>Tiered</strong></td>
<td>Free: 100/hr, Pro: 10000/hr</td>
<td>Commercial APIs</td>
</tr>
<tr class="odd">
<td><strong>Adaptive</strong></td>
<td>Reduce limits under high load</td>
<td>Self-protection</td>
</tr>
</tbody>
</table>
<hr>
</section>
</section>
<section id="q4-how-do-you-optimize-api-latency" class="level2">
<h2 class="anchored" data-anchor-id="q4-how-do-you-optimize-api-latency">Q4: How do you optimize API latency?</h2>
<p><strong>Answer:</strong></p>
<p>Latency optimization is a layered problem — you need to identify bottlenecks (usually I/O) and apply targeted strategies at each layer.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph LR
    subgraph Layers["Latency Optimization Layers"]
        direction TB
        L1["Network: CDN, compression, HTTP/2"]
        L2["Application: caching, async, batching"]
        L3["Database: indexes, query optimization, connection pools"]
        L4["Infrastructure: horizontal scaling, edge computing"]
    end

    style Layers fill:#56cc9d,stroke:#333,color:#fff
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="caching-strategies" class="level3">
<h3 class="anchored" data-anchor-id="caching-strategies">Caching Strategies</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> hashlib</span>
<span id="cb6-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> json</span>
<span id="cb6-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> functools <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> wraps</span>
<span id="cb6-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> redis.asyncio <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Redis</span>
<span id="cb6-5"></span>
<span id="cb6-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Layer 1: In-memory cache (per-worker, fastest)</span></span>
<span id="cb6-7"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> cachetools <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> TTLCache</span>
<span id="cb6-8">local_cache <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> TTLCache(maxsize<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>, ttl<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 30-second TTL</span></span>
<span id="cb6-9"></span>
<span id="cb6-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Layer 2: Redis cache (shared across workers)</span></span>
<span id="cb6-11"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> cache_response(redis: Redis, key: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>, ttl: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">300</span>):</span>
<span id="cb6-12">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Decorator for caching endpoint responses in Redis."""</span></span>
<span id="cb6-13">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> decorator(func):</span>
<span id="cb6-14">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@wraps</span>(func)</span>
<span id="cb6-15">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> wrapper(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>args, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>kwargs):</span>
<span id="cb6-16">            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Check cache</span></span>
<span id="cb6-17">            cached <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> redis.get(key)</span>
<span id="cb6-18">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> cached:</span>
<span id="cb6-19">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> json.loads(cached)</span>
<span id="cb6-20"></span>
<span id="cb6-21">            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Compute result</span></span>
<span id="cb6-22">            result <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> func(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>args, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>kwargs)</span>
<span id="cb6-23"></span>
<span id="cb6-24">            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Store in cache</span></span>
<span id="cb6-25">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> redis.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">set</span>(key, json.dumps(result), ex<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ttl)</span>
<span id="cb6-26">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> result</span>
<span id="cb6-27">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> wrapper</span>
<span id="cb6-28">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> decorator</span>
<span id="cb6-29"></span>
<span id="cb6-30"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Layer 3: HTTP cache headers</span></span>
<span id="cb6-31"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> fastapi.responses <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> JSONResponse</span>
<span id="cb6-32"></span>
<span id="cb6-33"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@app.get</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/api/v1/products/</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{product_id}</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb6-34"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_product(product_id: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>):</span>
<span id="cb6-35">    product <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> product_service.get(product_id)</span>
<span id="cb6-36">    response <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> JSONResponse(content<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>product.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>())</span>
<span id="cb6-37">    response.headers[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Cache-Control"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"public, max-age=60"</span></span>
<span id="cb6-38">    response.headers[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ETag"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> hashlib.md5(</span>
<span id="cb6-39">        json.dumps(product.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>()).encode()</span>
<span id="cb6-40">    ).hexdigest()</span>
<span id="cb6-41">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> response</span></code></pre></div></div>
</section>
<section id="database-query-optimization" class="level3">
<h3 class="anchored" data-anchor-id="database-query-optimization">Database Query Optimization</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># SLOW: N+1 query problem</span></span>
<span id="cb7-2"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_users_with_orders_slow():</span>
<span id="cb7-3">    users <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> db.fetch(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"SELECT * FROM users LIMIT 100"</span>)</span>
<span id="cb7-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> user <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> users:</span>
<span id="cb7-5">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 100 separate queries!</span></span>
<span id="cb7-6">        orders <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> db.fetch(</span>
<span id="cb7-7">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"SELECT * FROM orders WHERE user_id = $1"</span>, user[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"id"</span>]</span>
<span id="cb7-8">        )</span>
<span id="cb7-9">        user[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"orders"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> orders</span>
<span id="cb7-10"></span>
<span id="cb7-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># FAST: Single query with JOIN or batch</span></span>
<span id="cb7-12"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_users_with_orders_fast():</span>
<span id="cb7-13">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> db.fetch(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"""</span></span>
<span id="cb7-14"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">        SELECT u.*, json_agg(o.*) as orders</span></span>
<span id="cb7-15"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">        FROM users u</span></span>
<span id="cb7-16"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">        LEFT JOIN orders o ON o.user_id = u.id</span></span>
<span id="cb7-17"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">        GROUP BY u.id</span></span>
<span id="cb7-18"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">        LIMIT 100</span></span>
<span id="cb7-19"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    """</span>)</span>
<span id="cb7-20"></span>
<span id="cb7-21"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># FAST: Batch loading with IN clause</span></span>
<span id="cb7-22"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_users_with_orders_batch():</span>
<span id="cb7-23">    users <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> db.fetch(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"SELECT * FROM users LIMIT 100"</span>)</span>
<span id="cb7-24">    user_ids <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [u[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"id"</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> u <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> users]</span>
<span id="cb7-25">    orders <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> db.fetch(</span>
<span id="cb7-26">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"SELECT * FROM orders WHERE user_id = ANY($1)"</span>, user_ids</span>
<span id="cb7-27">    )</span>
<span id="cb7-28">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Group orders by user_id in Python</span></span>
<span id="cb7-29">    orders_by_user <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> defaultdict(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>)</span>
<span id="cb7-30">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> order <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> orders:</span>
<span id="cb7-31">        orders_by_user[order[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"user_id"</span>]].append(order)</span>
<span id="cb7-32">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> user <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> users:</span>
<span id="cb7-33">        user[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"orders"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> orders_by_user[user[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"id"</span>]]</span></code></pre></div></div>
</section>
<section id="latency-optimization-checklist" class="level3">
<h3 class="anchored" data-anchor-id="latency-optimization-checklist">Latency Optimization Checklist</h3>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Technique</th>
<th>Typical Improvement</th>
<th>Effort</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Add database indexes</td>
<td>10-100x for queries</td>
<td>Low</td>
</tr>
<tr class="even">
<td>Connection pooling</td>
<td>5-20ms per request</td>
<td>Low</td>
</tr>
<tr class="odd">
<td>Redis caching</td>
<td>50-500ms saved per cache hit</td>
<td>Medium</td>
</tr>
<tr class="even">
<td>Response compression (gzip)</td>
<td>50-80% smaller payloads</td>
<td>Low</td>
</tr>
<tr class="odd">
<td>Async I/O (avoid blocking)</td>
<td>Throughput, not latency</td>
<td>Medium</td>
</tr>
<tr class="even">
<td>Pagination (limit result size)</td>
<td>Prevents timeout</td>
<td>Low</td>
</tr>
<tr class="odd">
<td>N+1 query elimination</td>
<td>10-100x for list endpoints</td>
<td>Medium</td>
</tr>
<tr class="even">
<td>Background tasks (defer work)</td>
<td>Perceived latency reduction</td>
<td>Medium</td>
</tr>
<tr class="odd">
<td>Read replicas</td>
<td>Distribute read load</td>
<td>High</td>
</tr>
</tbody>
</table>
<hr>
</section>
</section>
<section id="q5-how-do-you-implement-authentication-and-authorization-in-a-python-api" class="level2">
<h2 class="anchored" data-anchor-id="q5-how-do-you-implement-authentication-and-authorization-in-a-python-api">Q5: How do you implement authentication and authorization in a Python API?</h2>
<p><strong>Answer:</strong></p>
<p><strong>Authentication</strong> verifies identity (“who are you?”). <strong>Authorization</strong> checks permissions (“what can you do?”). Production APIs typically use <strong>JWT tokens</strong> with <strong>OAuth2</strong> flows.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    LOGIN["POST /auth/login&lt;br/&gt;(email + password)"]
    LOGIN --&gt; VERIFY["Verify credentials&lt;br/&gt;(bcrypt hash check)"]
    VERIFY --&gt; TOKEN["Issue JWT Token&lt;br/&gt;(access + refresh)"]
    TOKEN --&gt; CLIENT["Client stores token"]

    CLIENT --&gt;|"Authorization: Bearer &lt;token&gt;"| API["Protected Endpoint"]
    API --&gt; DECODE["Decode &amp; verify JWT"]
    DECODE --&gt; AUTHZ["Check permissions&lt;br/&gt;(role-based / resource-based)"]
    AUTHZ --&gt; RESPONSE["Return data"]

    style LOGIN fill:#6cc3d5,stroke:#333,color:#fff
    style DECODE fill:#ffce67,stroke:#333
    style AUTHZ fill:#ff7851,stroke:#333,color:#fff
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="jwt-authentication-with-fastapi" class="level3">
<h3 class="anchored" data-anchor-id="jwt-authentication-with-fastapi">JWT Authentication with FastAPI</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> datetime <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> datetime, timedelta, timezone</span>
<span id="cb8-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> fastapi <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Depends, HTTPException, status</span>
<span id="cb8-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> fastapi.security <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> OAuth2PasswordBearer</span>
<span id="cb8-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> jose <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> JWTError, jwt</span>
<span id="cb8-5"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> passlib.context <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> CryptContext</span>
<span id="cb8-6"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> pydantic <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> BaseModel</span>
<span id="cb8-7"></span>
<span id="cb8-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Configuration</span></span>
<span id="cb8-9">SECRET_KEY <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> settings.secret_key  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># From environment, never hardcoded!</span></span>
<span id="cb8-10">ALGORITHM <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"HS256"</span></span>
<span id="cb8-11">ACCESS_TOKEN_EXPIRE_MINUTES <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span></span>
<span id="cb8-12"></span>
<span id="cb8-13">pwd_context <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> CryptContext(schemes<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bcrypt"</span>], deprecated<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"auto"</span>)</span>
<span id="cb8-14">oauth2_scheme <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> OAuth2PasswordBearer(tokenUrl<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/auth/login"</span>)</span>
<span id="cb8-15"></span>
<span id="cb8-16"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> TokenPayload(BaseModel):</span>
<span id="cb8-17">    sub: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Subject (user ID)</span></span>
<span id="cb8-18">    exp: datetime     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Expiration</span></span>
<span id="cb8-19">    role: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>         <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># User role</span></span>
<span id="cb8-20"></span>
<span id="cb8-21"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> create_access_token(user_id: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>, role: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>:</span>
<span id="cb8-22">    expire <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> datetime.now(timezone.utc) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> timedelta(minutes<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ACCESS_TOKEN_EXPIRE_MINUTES)</span>
<span id="cb8-23">    payload <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sub"</span>: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>(user_id), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"exp"</span>: expire, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"role"</span>: role}</span>
<span id="cb8-24">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> jwt.encode(payload, SECRET_KEY, algorithm<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ALGORITHM)</span>
<span id="cb8-25"></span>
<span id="cb8-26"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> verify_password(plain_password: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>, hashed_password: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bool</span>:</span>
<span id="cb8-27">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> pwd_context.verify(plain_password, hashed_password)</span>
<span id="cb8-28"></span>
<span id="cb8-29"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> hash_password(password: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>:</span>
<span id="cb8-30">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> pwd_context.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">hash</span>(password)</span>
<span id="cb8-31"></span>
<span id="cb8-32"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Dependency: extract and verify current user from JWT</span></span>
<span id="cb8-33"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_current_user(token: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Depends(oauth2_scheme)) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> User:</span>
<span id="cb8-34">    credentials_exception <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> HTTPException(</span>
<span id="cb8-35">        status_code<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>status.HTTP_401_UNAUTHORIZED,</span>
<span id="cb8-36">        detail<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Invalid authentication credentials"</span>,</span>
<span id="cb8-37">        headers<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>{<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"WWW-Authenticate"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Bearer"</span>},</span>
<span id="cb8-38">    )</span>
<span id="cb8-39">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">try</span>:</span>
<span id="cb8-40">        payload <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> jwt.decode(token, SECRET_KEY, algorithms<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[ALGORITHM])</span>
<span id="cb8-41">        user_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> payload.get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sub"</span>)</span>
<span id="cb8-42">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> user_id <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb8-43">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> credentials_exception</span>
<span id="cb8-44">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">except</span> JWTError:</span>
<span id="cb8-45">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> credentials_exception</span>
<span id="cb8-46"></span>
<span id="cb8-47">    user <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> user_service.get_by_id(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>(user_id))</span>
<span id="cb8-48">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> user <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb8-49">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> credentials_exception</span>
<span id="cb8-50">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> user</span></code></pre></div></div>
</section>
<section id="role-based-authorization" class="level3">
<h3 class="anchored" data-anchor-id="role-based-authorization">Role-Based Authorization</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> enum <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Enum</span>
<span id="cb9-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> functools <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> wraps</span>
<span id="cb9-3"></span>
<span id="cb9-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Role(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>, Enum):</span>
<span id="cb9-5">    USER <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"user"</span></span>
<span id="cb9-6">    ADMIN <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"admin"</span></span>
<span id="cb9-7">    MODERATOR <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"moderator"</span></span>
<span id="cb9-8"></span>
<span id="cb9-9"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> require_role(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>allowed_roles: Role):</span>
<span id="cb9-10">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Dependency that checks user role."""</span></span>
<span id="cb9-11">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> role_checker(current_user: User <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Depends(get_current_user)):</span>
<span id="cb9-12">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> current_user.role <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> allowed_roles:</span>
<span id="cb9-13">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> HTTPException(</span>
<span id="cb9-14">                status_code<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>status.HTTP_403_FORBIDDEN,</span>
<span id="cb9-15">                detail<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Insufficient permissions"</span>,</span>
<span id="cb9-16">            )</span>
<span id="cb9-17">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> current_user</span>
<span id="cb9-18">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> role_checker</span>
<span id="cb9-19"></span>
<span id="cb9-20"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Usage</span></span>
<span id="cb9-21"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@app.delete</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/api/v1/users/</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{user_id}</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb9-22"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> delete_user(</span>
<span id="cb9-23">    user_id: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>,</span>
<span id="cb9-24">    admin: User <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Depends(require_role(Role.ADMIN)),</span>
<span id="cb9-25">):</span>
<span id="cb9-26">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Only admins can delete users."""</span></span>
<span id="cb9-27">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> user_service.delete(user_id)</span>
<span id="cb9-28">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"status"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"deleted"</span>}</span>
<span id="cb9-29"></span>
<span id="cb9-30"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@app.get</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/api/v1/admin/stats"</span>)</span>
<span id="cb9-31"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> admin_stats(</span>
<span id="cb9-32">    user: User <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Depends(require_role(Role.ADMIN, Role.MODERATOR)),</span>
<span id="cb9-33">):</span>
<span id="cb9-34">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Admins and moderators can view stats."""</span></span>
<span id="cb9-35">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> stats_service.get_dashboard()</span></code></pre></div></div>
</section>
<section id="auth-best-practices" class="level3">
<h3 class="anchored" data-anchor-id="auth-best-practices">Auth Best Practices</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 66%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Practice</th>
<th>Why</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Hash passwords with bcrypt (cost factor ≥ 12)</td>
<td>Slow hashing resists brute force</td>
</tr>
<tr class="even">
<td>Short-lived access tokens (15-30 min)</td>
<td>Limits window of compromise</td>
</tr>
<tr class="odd">
<td>Use refresh tokens for long sessions</td>
<td>Access token rotation</td>
</tr>
<tr class="even">
<td>Store secrets in environment variables</td>
<td>Never in code or git</td>
</tr>
<tr class="odd">
<td>Validate token on every request</td>
<td>Stateless verification</td>
</tr>
<tr class="even">
<td>Use HTTPS always</td>
<td>Prevent token interception</td>
</tr>
<tr class="odd">
<td>Implement token revocation (blacklist)</td>
<td>Force logout / compromised tokens</td>
</tr>
</tbody>
</table>
<hr>
</section>
</section>
<section id="q6-how-do-you-protect-a-python-api-against-common-security-vulnerabilities" class="level2">
<h2 class="anchored" data-anchor-id="q6-how-do-you-protect-a-python-api-against-common-security-vulnerabilities">Q6: How do you protect a Python API against common security vulnerabilities?</h2>
<p><strong>Answer:</strong></p>
<p>Production APIs must defend against the <strong>OWASP Top 10</strong> web security risks. Python frameworks provide tools, but developers must use them correctly.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    THREATS["Common API Threats"]
    THREATS --&gt; INJ["Injection&lt;br/&gt;(SQL, NoSQL, Command)"]
    THREATS --&gt; AUTH["Broken Authentication"]
    THREATS --&gt; EXPO["Data Exposure&lt;br/&gt;(Sensitive data in responses)"]
    THREATS --&gt; MASS["Mass Assignment&lt;br/&gt;(Unvalidated input fields)"]
    THREATS --&gt; RATE["Lack of Rate Limiting"]
    THREATS --&gt; SSRF["SSRF&lt;br/&gt;(Server-Side Request Forgery)"]

    subgraph Defenses["Defense Layers"]
        D1["Input Validation (Pydantic)"]
        D2["Parameterized Queries"]
        D3["Output Filtering"]
        D4["CORS Configuration"]
        D5["Security Headers"]
        D6["Rate Limiting"]
    end

    style THREATS fill:#ff7851,stroke:#333,color:#fff
    style Defenses fill:#56cc9d,stroke:#333,color:#fff
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="sql-injection-prevention" class="level3">
<h3 class="anchored" data-anchor-id="sql-injection-prevention">SQL Injection Prevention</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># VULNERABLE: String formatting in SQL</span></span>
<span id="cb10-2"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_user_unsafe(username: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>):</span>
<span id="cb10-3">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># NEVER DO THIS — SQL injection!</span></span>
<span id="cb10-4">    query <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"SELECT * FROM users WHERE username = '</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>username<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">'"</span></span>
<span id="cb10-5">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> db.fetch(query)</span>
<span id="cb10-6">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Attack: username = "'; DROP TABLE users; --"</span></span>
<span id="cb10-7"></span>
<span id="cb10-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># SAFE: Parameterized queries (always use these)</span></span>
<span id="cb10-9"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_user_safe(username: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>):</span>
<span id="cb10-10">    query <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"SELECT * FROM users WHERE username = $1"</span></span>
<span id="cb10-11">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> db.fetchrow(query, username)</span>
<span id="cb10-12">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Parameters are escaped automatically</span></span>
<span id="cb10-13"></span>
<span id="cb10-14"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># SAFE: ORM (SQLAlchemy, Tortoise)</span></span>
<span id="cb10-15"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_user_orm(username: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>):</span>
<span id="cb10-16">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> User.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">filter</span>(username<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>username).first()</span></code></pre></div></div>
</section>
<section id="input-validation-and-mass-assignment-protection" class="level3">
<h3 class="anchored" data-anchor-id="input-validation-and-mass-assignment-protection">Input Validation and Mass Assignment Protection</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> pydantic <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> BaseModel, Field, field_validator</span>
<span id="cb11-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> re</span>
<span id="cb11-3"></span>
<span id="cb11-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> UserCreate(BaseModel):</span>
<span id="cb11-5">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Only these fields are accepted — everything else is ignored."""</span></span>
<span id="cb11-6">    name: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Field(..., min_length<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, max_length<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>)</span>
<span id="cb11-7">    email: EmailStr</span>
<span id="cb11-8">    password: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Field(..., min_length<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>, max_length<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">128</span>)</span>
<span id="cb11-9"></span>
<span id="cb11-10">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@field_validator</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"name"</span>)</span>
<span id="cb11-11">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@classmethod</span></span>
<span id="cb11-12">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> validate_name(cls, v: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>:</span>
<span id="cb11-13">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> re.match(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">^</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[a-zA-Z</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">\s</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\-</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">']</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">$</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>, v):</span>
<span id="cb11-14">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">ValueError</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Name contains invalid characters"</span>)</span>
<span id="cb11-15">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> v.strip()</span>
<span id="cb11-16"></span>
<span id="cb11-17">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@field_validator</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"password"</span>)</span>
<span id="cb11-18">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@classmethod</span></span>
<span id="cb11-19">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> validate_password(cls, v: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>:</span>
<span id="cb11-20">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> re.search(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[A-Z]</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>, v):</span>
<span id="cb11-21">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">ValueError</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Password must contain an uppercase letter"</span>)</span>
<span id="cb11-22">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> re.search(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[0-9]</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>, v):</span>
<span id="cb11-23">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">ValueError</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Password must contain a digit"</span>)</span>
<span id="cb11-24">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> v</span>
<span id="cb11-25"></span>
<span id="cb11-26"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Mass assignment protection: UserCreate does NOT have 'role' or 'is_admin'</span></span>
<span id="cb11-27"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Even if client sends {"name": "Alice", "role": "admin"}, role is ignored</span></span>
<span id="cb11-28"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@app.post</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/api/v1/users"</span>)</span>
<span id="cb11-29"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> create_user(data: UserCreate):  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Only name, email, password accepted</span></span>
<span id="cb11-30">    user <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> user_service.create(data)</span>
<span id="cb11-31">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> UserResponse.model_validate(user)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Only safe fields in response</span></span></code></pre></div></div>
</section>
<section id="security-headers-and-cors" class="level3">
<h3 class="anchored" data-anchor-id="security-headers-and-cors">Security Headers and CORS</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> fastapi.middleware.cors <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> CORSMiddleware</span>
<span id="cb12-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> fastapi.middleware.trustedhost <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> TrustedHostMiddleware</span>
<span id="cb12-3"></span>
<span id="cb12-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># CORS: restrict which origins can call your API</span></span>
<span id="cb12-5">app.add_middleware(</span>
<span id="cb12-6">    CORSMiddleware,</span>
<span id="cb12-7">    allow_origins<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"https://myapp.com"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"https://admin.myapp.com"</span>],</span>
<span id="cb12-8">    allow_credentials<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>,</span>
<span id="cb12-9">    allow_methods<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"GET"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"POST"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"PUT"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"DELETE"</span>],</span>
<span id="cb12-10">    allow_headers<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Authorization"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Content-Type"</span>],</span>
<span id="cb12-11">)</span>
<span id="cb12-12"></span>
<span id="cb12-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Trusted hosts: prevent Host header attacks</span></span>
<span id="cb12-14">app.add_middleware(TrustedHostMiddleware, allowed_hosts<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"api.myapp.com"</span>])</span>
<span id="cb12-15"></span>
<span id="cb12-16"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Security headers middleware</span></span>
<span id="cb12-17"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@app.middleware</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"http"</span>)</span>
<span id="cb12-18"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> add_security_headers(request, call_next):</span>
<span id="cb12-19">    response <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> call_next(request)</span>
<span id="cb12-20">    response.headers[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"X-Content-Type-Options"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nosniff"</span></span>
<span id="cb12-21">    response.headers[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"X-Frame-Options"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"DENY"</span></span>
<span id="cb12-22">    response.headers[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Strict-Transport-Security"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"max-age=31536000; includeSubDomains"</span></span>
<span id="cb12-23">    response.headers[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"X-XSS-Protection"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1; mode=block"</span></span>
<span id="cb12-24">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> response</span></code></pre></div></div>
</section>
<section id="security-checklist" class="level3">
<h3 class="anchored" data-anchor-id="security-checklist">Security Checklist</h3>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Vulnerability</th>
<th>Defense</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>SQL Injection</td>
<td>Parameterized queries / ORM</td>
</tr>
<tr class="even">
<td>Mass Assignment</td>
<td>Pydantic models with explicit fields</td>
</tr>
<tr class="odd">
<td>Broken Auth</td>
<td>JWT + bcrypt + short expiry</td>
</tr>
<tr class="even">
<td>Data Exposure</td>
<td>Response models that exclude sensitive fields</td>
</tr>
<tr class="odd">
<td>SSRF</td>
<td>Validate/whitelist URLs before fetching</td>
</tr>
<tr class="even">
<td>DoS</td>
<td>Rate limiting + request size limits</td>
</tr>
<tr class="odd">
<td>XSS (if serving HTML)</td>
<td>Template escaping, CSP headers</td>
</tr>
<tr class="even">
<td>CSRF</td>
<td>SameSite cookies + CSRF tokens</td>
</tr>
</tbody>
</table>
<hr>
</section>
</section>
<section id="q7-how-do-you-implement-background-tasks-and-task-queues" class="level2">
<h2 class="anchored" data-anchor-id="q7-how-do-you-implement-background-tasks-and-task-queues">Q7: How do you implement background tasks and task queues?</h2>
<p><strong>Answer:</strong></p>
<p>Not all work should happen in the request-response cycle. <strong>Background tasks</strong> handle deferred work (emails, notifications), while <strong>task queues</strong> handle heavy/long-running jobs (report generation, ML inference).</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph LR
    API["API Server"]
    API --&gt;|"lightweight"| BG["Background Tasks&lt;br/&gt;(in-process)"]
    API --&gt;|"heavy/reliable"| QUEUE["Task Queue&lt;br/&gt;(Celery / arq)"]

    QUEUE --&gt; WORKER["Worker Process(es)"]
    WORKER --&gt; DB["Database"]
    WORKER --&gt; EMAIL["Email Service"]
    WORKER --&gt; ML["ML Model"]

    subgraph InProcess["In-Process (FastAPI BackgroundTasks)"]
        BG1["Send email"]
        BG2["Write audit log"]
        BG3["Update cache"]
    end

    subgraph Distributed["Distributed (Celery / arq)"]
        Q1["Generate PDF report"]
        Q2["Process video upload"]
        Q3["Run ML pipeline"]
        Q4["Bulk data import"]
    end

    style API fill:#56cc9d,stroke:#333,color:#fff
    style QUEUE fill:#ffce67,stroke:#333
    style WORKER fill:#6cc3d5,stroke:#333,color:#fff
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="fastapi-background-tasks-lightweight" class="level3">
<h3 class="anchored" data-anchor-id="fastapi-background-tasks-lightweight">FastAPI Background Tasks (Lightweight)</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> fastapi <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> BackgroundTasks</span>
<span id="cb13-2"></span>
<span id="cb13-3"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> send_welcome_email(email: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>, name: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>):</span>
<span id="cb13-4">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Runs after response is sent — doesn't block the client."""</span></span>
<span id="cb13-5">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> email_service.send(</span>
<span id="cb13-6">        to<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>email,</span>
<span id="cb13-7">        subject<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Welcome!"</span>,</span>
<span id="cb13-8">        body<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Hi </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>name<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">, welcome to our platform!"</span></span>
<span id="cb13-9">    )</span>
<span id="cb13-10"></span>
<span id="cb13-11"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> log_signup(user_id: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>):</span>
<span id="cb13-12">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> analytics.track(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"user_signup"</span>, user_id<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>user_id)</span>
<span id="cb13-13"></span>
<span id="cb13-14"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@app.post</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/api/v1/users"</span>, status_code<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">201</span>)</span>
<span id="cb13-15"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> create_user(data: UserCreate, background_tasks: BackgroundTasks):</span>
<span id="cb13-16">    user <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> user_service.create(data)</span>
<span id="cb13-17"></span>
<span id="cb13-18">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># These run AFTER the response is returned to the client</span></span>
<span id="cb13-19">    background_tasks.add_task(send_welcome_email, user.email, user.name)</span>
<span id="cb13-20">    background_tasks.add_task(log_signup, user.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">id</span>)</span>
<span id="cb13-21"></span>
<span id="cb13-22">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> UserResponse.model_validate(user)</span>
<span id="cb13-23">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Client gets 201 immediately — doesn't wait for email</span></span></code></pre></div></div>
</section>
<section id="distributed-task-queue-arq-async-native" class="level3">
<h3 class="anchored" data-anchor-id="distributed-task-queue-arq-async-native">Distributed Task Queue (arq — async-native)</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb14-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># tasks.py — define tasks</span></span>
<span id="cb14-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> arq <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> create_pool</span>
<span id="cb14-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> arq.connections <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> RedisSettings</span>
<span id="cb14-4"></span>
<span id="cb14-5"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> generate_report(ctx, user_id: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>, report_type: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>):</span>
<span id="cb14-6">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Heavy task — runs in a separate worker process."""</span></span>
<span id="cb14-7">    data <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> fetch_report_data(user_id, report_type)</span>
<span id="cb14-8">    pdf <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> render_pdf(data)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># CPU-intensive</span></span>
<span id="cb14-9">    url <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> upload_to_s3(pdf)</span>
<span id="cb14-10">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> notify_user(user_id, <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Report ready: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>url<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb14-11">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"url"</span>: url}</span>
<span id="cb14-12"></span>
<span id="cb14-13"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> process_image(ctx, image_id: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>):</span>
<span id="cb14-14">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Image processing — CPU-bound, offloaded to worker."""</span></span>
<span id="cb14-15">    image <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> download_image(image_id)</span>
<span id="cb14-16">    thumbnails <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> create_thumbnails(image, sizes<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">128</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">256</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">512</span>])</span>
<span id="cb14-17">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> save_thumbnails(image_id, thumbnails)</span>
<span id="cb14-18"></span>
<span id="cb14-19"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Worker configuration</span></span>
<span id="cb14-20"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> WorkerSettings:</span>
<span id="cb14-21">    functions <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [generate_report, process_image]</span>
<span id="cb14-22">    redis_settings <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> RedisSettings(host<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"redis"</span>)</span>
<span id="cb14-23">    max_jobs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span></span>
<span id="cb14-24"></span>
<span id="cb14-25"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># API endpoint — enqueue task</span></span>
<span id="cb14-26"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@app.post</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/api/v1/reports"</span>)</span>
<span id="cb14-27"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> request_report(user_id: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>, report_type: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>):</span>
<span id="cb14-28">    redis <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> create_pool(RedisSettings(host<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"redis"</span>))</span>
<span id="cb14-29">    job <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> redis.enqueue_job(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"generate_report"</span>, user_id, report_type)</span>
<span id="cb14-30">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"job_id"</span>: job.job_id, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"status"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"queued"</span>}</span></code></pre></div></div>
</section>
<section id="when-to-use-what" class="level3">
<h3 class="anchored" data-anchor-id="when-to-use-what">When to Use What</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 31%">
<col style="width: 31%">
<col style="width: 37%">
</colgroup>
<thead>
<tr class="header">
<th>Approach</th>
<th>Use Case</th>
<th>Guarantees</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>BackgroundTasks</code></td>
<td>Email, logging, cache updates</td>
<td>Best-effort (lost if server crashes)</td>
</tr>
<tr class="even">
<td>arq / Celery</td>
<td>Reports, heavy processing, ML</td>
<td>Reliable (persisted in Redis/RabbitMQ)</td>
</tr>
<tr class="odd">
<td>Cron / scheduler</td>
<td>Periodic cleanup, daily reports</td>
<td>Scheduled execution</td>
</tr>
<tr class="even">
<td>Streaming response</td>
<td>Real-time progress updates</td>
<td>Client stays connected</td>
</tr>
</tbody>
</table>
<hr>
</section>
</section>
<section id="q8-how-do-you-handle-api-versioning-and-backward-compatibility" class="level2">
<h2 class="anchored" data-anchor-id="q8-how-do-you-handle-api-versioning-and-backward-compatibility">Q8: How do you handle API versioning and backward compatibility?</h2>
<p><strong>Answer:</strong></p>
<p>APIs evolve, but breaking changes destroy client trust. Versioning strategies let you evolve without breaking existing consumers.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    subgraph Strategies["Versioning Strategies"]
        URL["URL Path&lt;br/&gt;/api/v1/users&lt;br/&gt;/api/v2/users"]
        HEADER["Header&lt;br/&gt;Accept: application/vnd.api+json;version=2"]
        QUERY["Query Param&lt;br/&gt;/api/users?version=2"]
    end

    URL --&gt; REC["✓ Most common&lt;br/&gt;✓ Easy to understand&lt;br/&gt;✓ Cacheable"]
    HEADER --&gt; ADV["✓ Clean URLs&lt;br/&gt;✗ Harder to test&lt;br/&gt;✗ Not visible in logs"]

    style URL fill:#56cc9d,stroke:#333,color:#fff
    style REC fill:#6cc3d5,stroke:#333,color:#fff
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="url-based-versioning-recommended" class="level3">
<h3 class="anchored" data-anchor-id="url-based-versioning-recommended">URL-Based Versioning (Recommended)</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb15-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> fastapi <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> APIRouter</span>
<span id="cb15-2"></span>
<span id="cb15-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Version 1</span></span>
<span id="cb15-4">v1_router <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> APIRouter(prefix<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/api/v1"</span>)</span>
<span id="cb15-5"></span>
<span id="cb15-6"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@v1_router.get</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/users/</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{user_id}</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb15-7"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_user_v1(user_id: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>):</span>
<span id="cb15-8">    user <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> user_service.get(user_id)</span>
<span id="cb15-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"id"</span>: user.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">id</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"name"</span>: user.name, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"email"</span>: user.email}</span>
<span id="cb15-10"></span>
<span id="cb15-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Version 2 — adds new fields, changes format</span></span>
<span id="cb15-12">v2_router <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> APIRouter(prefix<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/api/v2"</span>)</span>
<span id="cb15-13"></span>
<span id="cb15-14"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@v2_router.get</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/users/</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{user_id}</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb15-15"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_user_v2(user_id: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>):</span>
<span id="cb15-16">    user <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> user_service.get(user_id)</span>
<span id="cb15-17">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> {</span>
<span id="cb15-18">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"id"</span>: user.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">id</span>,</span>
<span id="cb15-19">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"name"</span>: {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"first"</span>: user.first_name, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"last"</span>: user.last_name},</span>
<span id="cb15-20">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"email"</span>: user.email,</span>
<span id="cb15-21">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"created_at"</span>: user.created_at.isoformat(),</span>
<span id="cb15-22">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"links"</span>: {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"self"</span>: <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"/api/v2/users/</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>user<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">id</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>},</span>
<span id="cb15-23">    }</span>
<span id="cb15-24"></span>
<span id="cb15-25">app.include_router(v1_router)</span>
<span id="cb15-26">app.include_router(v2_router)</span></code></pre></div></div>
</section>
<section id="backward-compatible-changes-no-version-bump-needed" class="level3">
<h3 class="anchored" data-anchor-id="backward-compatible-changes-no-version-bump-needed">Backward-Compatible Changes (No Version Bump Needed)</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 46%">
<col style="width: 53%">
</colgroup>
<thead>
<tr class="header">
<th>Safe Change</th>
<th>Why It’s Safe</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Add a new optional field to response</td>
<td>Existing clients ignore unknown fields</td>
</tr>
<tr class="even">
<td>Add a new endpoint</td>
<td>No conflict with existing routes</td>
</tr>
<tr class="odd">
<td>Add optional query parameter</td>
<td>Existing calls still work without it</td>
</tr>
<tr class="even">
<td>Add a new enum value to response</td>
<td>Clients should handle unknown values</td>
</tr>
</tbody>
</table>
</section>
<section id="breaking-changes-require-new-version" class="level3">
<h3 class="anchored" data-anchor-id="breaking-changes-require-new-version">Breaking Changes (Require New Version)</h3>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Breaking Change</th>
<th>Why It Breaks</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Remove or rename a field</td>
<td>Clients accessing it get errors</td>
</tr>
<tr class="even">
<td>Change field type (<code>string</code> → <code>int</code>)</td>
<td>Parsing fails</td>
</tr>
<tr class="odd">
<td>Make optional field required</td>
<td>Existing requests missing it fail</td>
</tr>
<tr class="even">
<td>Change URL structure</td>
<td>Existing bookmarks/integrations break</td>
</tr>
<tr class="odd">
<td>Change error format</td>
<td>Client error handling breaks</td>
</tr>
</tbody>
</table>
</section>
<section id="deprecation-strategy" class="level3">
<h3 class="anchored" data-anchor-id="deprecation-strategy">Deprecation Strategy</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb16-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> warnings</span>
<span id="cb16-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> fastapi <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Header</span>
<span id="cb16-3"></span>
<span id="cb16-4"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@v1_router.get</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/users/</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{user_id}</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>, deprecated<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Shows in OpenAPI docs</span></span>
<span id="cb16-5"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_user_v1(user_id: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>):</span>
<span id="cb16-6">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Deprecated: Use /api/v2/users/{user_id} instead."""</span></span>
<span id="cb16-7">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Add sunset header</span></span>
<span id="cb16-8">    response.headers[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Sunset"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Sat, 01 Jan 2027 00:00:00 GMT"</span></span>
<span id="cb16-9">    response.headers[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Deprecation"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"true"</span></span>
<span id="cb16-10">    response.headers[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Link"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'&lt;/api/v2/users&gt;; rel="successor-version"'</span></span>
<span id="cb16-11">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> get_user_legacy(user_id)</span></code></pre></div></div>
<hr>
</section>
</section>
<section id="q9-how-do-you-implement-health-checks-and-observability" class="level2">
<h2 class="anchored" data-anchor-id="q9-how-do-you-implement-health-checks-and-observability">Q9: How do you implement health checks and observability?</h2>
<p><strong>Answer:</strong></p>
<p>Production APIs need <strong>health checks</strong> (for load balancers and orchestrators), <strong>metrics</strong> (for dashboards), and <strong>distributed tracing</strong> (for debugging latency across services).</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    OBS["Observability Stack"]
    OBS --&gt; HEALTH["Health Checks&lt;br/&gt;/health, /ready"]
    OBS --&gt; METRICS["Metrics&lt;br/&gt;Prometheus + Grafana"]
    OBS --&gt; TRACES["Distributed Tracing&lt;br/&gt;OpenTelemetry"]
    OBS --&gt; LOGS["Structured Logs&lt;br/&gt;JSON → ELK/Loki"]

    HEALTH --&gt; LB["Load Balancer&lt;br/&gt;Route traffic to healthy instances"]
    HEALTH --&gt; K8S["Kubernetes&lt;br/&gt;Restart unhealthy pods"]

    style OBS fill:#56cc9d,stroke:#333,color:#fff
    style HEALTH fill:#6cc3d5,stroke:#333,color:#fff
    style METRICS fill:#ffce67,stroke:#333
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="health-check-endpoints" class="level3">
<h3 class="anchored" data-anchor-id="health-check-endpoints">Health Check Endpoints</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb17-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> fastapi <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> FastAPI, status</span>
<span id="cb17-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> pydantic <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> BaseModel</span>
<span id="cb17-3"></span>
<span id="cb17-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> HealthResponse(BaseModel):</span>
<span id="cb17-5">    status: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span></span>
<span id="cb17-6">    checks: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>]</span>
<span id="cb17-7"></span>
<span id="cb17-8"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@app.get</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/health/live"</span>, status_code<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span>)</span>
<span id="cb17-9"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> liveness():</span>
<span id="cb17-10">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Is the process alive? (Kubernetes liveness probe)"""</span></span>
<span id="cb17-11">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"status"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"alive"</span>}</span>
<span id="cb17-12"></span>
<span id="cb17-13"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@app.get</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/health/ready"</span>, response_model<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>HealthResponse)</span>
<span id="cb17-14"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> readiness():</span>
<span id="cb17-15">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Can the service handle traffic? Check dependencies."""</span></span>
<span id="cb17-16">    checks <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {}</span>
<span id="cb17-17"></span>
<span id="cb17-18">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Check database</span></span>
<span id="cb17-19">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">try</span>:</span>
<span id="cb17-20">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> app.state.db_pool.fetchval(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"SELECT 1"</span>)</span>
<span id="cb17-21">        checks[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"database"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"healthy"</span></span>
<span id="cb17-22">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">except</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">Exception</span>:</span>
<span id="cb17-23">        checks[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"database"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"unhealthy"</span></span>
<span id="cb17-24"></span>
<span id="cb17-25">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Check Redis</span></span>
<span id="cb17-26">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">try</span>:</span>
<span id="cb17-27">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> app.state.redis.ping()</span>
<span id="cb17-28">        checks[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"redis"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"healthy"</span></span>
<span id="cb17-29">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">except</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">Exception</span>:</span>
<span id="cb17-30">        checks[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"redis"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"unhealthy"</span></span>
<span id="cb17-31"></span>
<span id="cb17-32">    all_healthy <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">all</span>(v <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"healthy"</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> v <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> checks.values())</span>
<span id="cb17-33"></span>
<span id="cb17-34">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> all_healthy:</span>
<span id="cb17-35">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> HTTPException(</span>
<span id="cb17-36">            status_code<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>status.HTTP_503_SERVICE_UNAVAILABLE,</span>
<span id="cb17-37">            detail<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>{<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"status"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"unhealthy"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"checks"</span>: checks},</span>
<span id="cb17-38">        )</span>
<span id="cb17-39">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> HealthResponse(status<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"healthy"</span>, checks<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>checks)</span></code></pre></div></div>
</section>
<section id="request-metrics-middleware" class="level3">
<h3 class="anchored" data-anchor-id="request-metrics-middleware">Request Metrics Middleware</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb18-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> time</span>
<span id="cb18-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> prometheus_client <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Counter, Histogram, generate_latest</span>
<span id="cb18-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> starlette.middleware.base <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> BaseHTTPMiddleware</span>
<span id="cb18-4"></span>
<span id="cb18-5">REQUEST_COUNT <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Counter(</span>
<span id="cb18-6">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"http_requests_total"</span>,</span>
<span id="cb18-7">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Total HTTP requests"</span>,</span>
<span id="cb18-8">    [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"method"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"endpoint"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"status_code"</span>],</span>
<span id="cb18-9">)</span>
<span id="cb18-10">REQUEST_LATENCY <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Histogram(</span>
<span id="cb18-11">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"http_request_duration_seconds"</span>,</span>
<span id="cb18-12">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"HTTP request latency"</span>,</span>
<span id="cb18-13">    [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"method"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"endpoint"</span>],</span>
<span id="cb18-14">    buckets<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.25</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">5.0</span>],</span>
<span id="cb18-15">)</span>
<span id="cb18-16"></span>
<span id="cb18-17"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> MetricsMiddleware(BaseHTTPMiddleware):</span>
<span id="cb18-18">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> dispatch(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, request, call_next):</span>
<span id="cb18-19">        start <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> time.perf_counter()</span>
<span id="cb18-20">        response <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> call_next(request)</span>
<span id="cb18-21">        duration <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> time.perf_counter() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> start</span>
<span id="cb18-22"></span>
<span id="cb18-23">        endpoint <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> request.url.path</span>
<span id="cb18-24">        REQUEST_COUNT.labels(request.method, endpoint, response.status_code).inc()</span>
<span id="cb18-25">        REQUEST_LATENCY.labels(request.method, endpoint).observe(duration)</span>
<span id="cb18-26"></span>
<span id="cb18-27">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> response</span>
<span id="cb18-28"></span>
<span id="cb18-29">app.add_middleware(MetricsMiddleware)</span>
<span id="cb18-30"></span>
<span id="cb18-31"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@app.get</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/metrics"</span>)</span>
<span id="cb18-32"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> metrics():</span>
<span id="cb18-33">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Prometheus scrape endpoint."""</span></span>
<span id="cb18-34">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> Response(content<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>generate_latest(), media_type<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text/plain"</span>)</span></code></pre></div></div>
</section>
<section id="key-metrics-to-track" class="level3">
<h3 class="anchored" data-anchor-id="key-metrics-to-track">Key Metrics to Track</h3>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Metric</th>
<th>What It Tells You</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Request rate (req/s)</td>
<td>Traffic volume and trends</td>
</tr>
<tr class="even">
<td>Latency percentiles (p50, p95, p99)</td>
<td>User experience</td>
</tr>
<tr class="odd">
<td>Error rate (5xx / total)</td>
<td>System reliability</td>
</tr>
<tr class="even">
<td>DB connection pool utilization</td>
<td>Capacity planning</td>
</tr>
<tr class="odd">
<td>Queue depth / task latency</td>
<td>Background job health</td>
</tr>
<tr class="even">
<td>Cache hit ratio</td>
<td>Caching effectiveness</td>
</tr>
</tbody>
</table>
<hr>
</section>
</section>
<section id="q10-how-do-you-handle-graceful-shutdown-and-zero-downtime-deployments" class="level2">
<h2 class="anchored" data-anchor-id="q10-how-do-you-handle-graceful-shutdown-and-zero-downtime-deployments">Q10: How do you handle graceful shutdown and zero-downtime deployments?</h2>
<p><strong>Answer:</strong></p>
<p>Production APIs must handle shutdowns without dropping in-flight requests and deploy new versions without user-visible downtime.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    subgraph Shutdown["Graceful Shutdown Flow"]
        direction TB
        SIG["SIGTERM received"]
        SIG --&gt; STOP["Stop accepting new requests"]
        STOP --&gt; DRAIN["Drain in-flight requests&lt;br/&gt;(wait for completion)"]
        DRAIN --&gt; CLEANUP["Close connections&lt;br/&gt;(DB pools, Redis, files)"]
        CLEANUP --&gt; EXIT["Process exits cleanly"]
    end

    subgraph Deploy["Zero-Downtime Deploy"]
        direction TB
        D1["Start new instances"]
        D1 --&gt; D2["Health check passes"]
        D2 --&gt; D3["Route traffic to new instances"]
        D3 --&gt; D4["Drain old instances"]
        D4 --&gt; D5["Stop old instances"]
    end

    style Shutdown fill:#6cc3d5,stroke:#333,color:#fff
    style Deploy fill:#56cc9d,stroke:#333,color:#fff
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="graceful-shutdown-in-fastapi" class="level3">
<h3 class="anchored" data-anchor-id="graceful-shutdown-in-fastapi">Graceful Shutdown in FastAPI</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb19-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> signal</span>
<span id="cb19-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> asyncio</span>
<span id="cb19-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> contextlib <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> asynccontextmanager</span>
<span id="cb19-4"></span>
<span id="cb19-5"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@asynccontextmanager</span></span>
<span id="cb19-6"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> lifespan(app: FastAPI):</span>
<span id="cb19-7">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># STARTUP</span></span>
<span id="cb19-8">    app.state.db_pool <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> create_db_pool()</span>
<span id="cb19-9">    app.state.redis <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> create_redis_pool()</span>
<span id="cb19-10">    app.state.task_queue <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> TaskQueue()</span>
<span id="cb19-11"></span>
<span id="cb19-12">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">yield</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Application runs here</span></span>
<span id="cb19-13"></span>
<span id="cb19-14">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># SHUTDOWN (triggered by SIGTERM)</span></span>
<span id="cb19-15">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 1. Stop accepting new background tasks</span></span>
<span id="cb19-16">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> app.state.task_queue.stop()</span>
<span id="cb19-17"></span>
<span id="cb19-18">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 2. Wait for in-flight background tasks to complete (with timeout)</span></span>
<span id="cb19-19">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> asyncio.wait_for(</span>
<span id="cb19-20">        app.state.task_queue.drain(),</span>
<span id="cb19-21">        timeout<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>,  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Force exit after 30s</span></span>
<span id="cb19-22">    )</span>
<span id="cb19-23"></span>
<span id="cb19-24">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 3. Close external connections</span></span>
<span id="cb19-25">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> app.state.db_pool.close()</span>
<span id="cb19-26">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> app.state.redis.close()</span>
<span id="cb19-27"></span>
<span id="cb19-28">app <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> FastAPI(lifespan<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>lifespan)</span></code></pre></div></div>
</section>
<section id="gunicorn-graceful-shutdown" class="level3">
<h3 class="anchored" data-anchor-id="gunicorn-graceful-shutdown">Gunicorn Graceful Shutdown</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb20" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb20-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># gunicorn.conf.py</span></span>
<span id="cb20-2">graceful_timeout <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Seconds to wait for workers to finish requests</span></span>
<span id="cb20-3">timeout <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60</span>           <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Max time for a single request</span></span>
<span id="cb20-4"></span>
<span id="cb20-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Pre-fork hook: setup signal handling</span></span>
<span id="cb20-6"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> worker_exit(server, worker):</span>
<span id="cb20-7">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Called when a worker is shutting down."""</span></span>
<span id="cb20-8">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Cleanup worker-specific resources</span></span>
<span id="cb20-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pass</span></span></code></pre></div></div>
</section>
<section id="zero-downtime-deployment-strategies" class="level3">
<h3 class="anchored" data-anchor-id="zero-downtime-deployment-strategies">Zero-Downtime Deployment Strategies</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 28%">
<col style="width: 37%">
<col style="width: 34%">
</colgroup>
<thead>
<tr class="header">
<th>Strategy</th>
<th>How It Works</th>
<th>Complexity</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>Rolling update</strong></td>
<td>Replace instances one at a time</td>
<td>Low (K8s default)</td>
</tr>
<tr class="even">
<td><strong>Blue-green</strong></td>
<td>Run two full environments, switch traffic</td>
<td>Medium</td>
</tr>
<tr class="odd">
<td><strong>Canary</strong></td>
<td>Route small % of traffic to new version</td>
<td>High</td>
</tr>
</tbody>
</table>
</section>
<section id="kubernetes-configuration" class="level3">
<h3 class="anchored" data-anchor-id="kubernetes-configuration">Kubernetes Configuration</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb21-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Deployment with graceful shutdown support</span></span>
<span id="cb21-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">apiVersion</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> apps/v1</span></span>
<span id="cb21-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">kind</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> Deployment</span></span>
<span id="cb21-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">spec</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span></span>
<span id="cb21-5"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">  </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicas</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span></span>
<span id="cb21-6"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">  </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">strategy</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span></span>
<span id="cb21-7"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">    </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">type</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> RollingUpdate</span></span>
<span id="cb21-8"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">    </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rollingUpdate</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span></span>
<span id="cb21-9"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">      </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">maxUnavailable</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb21-10"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">      </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">maxSurge</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb21-11"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">  </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">template</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span></span>
<span id="cb21-12"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">    </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">spec</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span></span>
<span id="cb21-13"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">      </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">terminationGracePeriodSeconds</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">45</span><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">  # Time for graceful shutdown</span></span>
<span id="cb21-14"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">      </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">containers</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span></span>
<span id="cb21-15"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">        </span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">-</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">name</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> api</span></span>
<span id="cb21-16"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">          </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">livenessProbe</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span></span>
<span id="cb21-17"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">            </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">httpGet</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span></span>
<span id="cb21-18"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">              </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">path</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> /health/live</span></span>
<span id="cb21-19"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">              </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">port</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8000</span></span>
<span id="cb21-20"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">            </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">initialDelaySeconds</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span></span>
<span id="cb21-21"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">            </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">periodSeconds</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span></span>
<span id="cb21-22"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">          </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">readinessProbe</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span></span>
<span id="cb21-23"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">            </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">httpGet</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span></span>
<span id="cb21-24"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">              </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">path</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> /health/ready</span></span>
<span id="cb21-25"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">              </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">port</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8000</span></span>
<span id="cb21-26"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">            </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">initialDelaySeconds</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span></span>
<span id="cb21-27"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">            </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">periodSeconds</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span></span>
<span id="cb21-28"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">          </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lifecycle</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span></span>
<span id="cb21-29"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">            </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">preStop</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span></span>
<span id="cb21-30"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">              </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exec</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span></span>
<span id="cb21-31"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">                </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">command</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">[</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sleep"</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">,</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"5"</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">]</span><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">  # Allow LB to deregister</span></span></code></pre></div></div>
</section>
<section id="deployment-checklist" class="level3">
<h3 class="anchored" data-anchor-id="deployment-checklist">Deployment Checklist</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 40%">
<col style="width: 60%">
</colgroup>
<thead>
<tr class="header">
<th>Step</th>
<th>Purpose</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Run database migrations first</td>
<td>Schema supports both old and new code</td>
</tr>
<tr class="even">
<td>Deploy new version alongside old</td>
<td>Both must work concurrently</td>
</tr>
<tr class="odd">
<td>Health checks pass before routing traffic</td>
<td>Catch startup failures</td>
</tr>
<tr class="even">
<td>Drain connections before stopping old</td>
<td>No dropped requests</td>
</tr>
<tr class="odd">
<td>Monitor error rates after deploy</td>
<td>Catch regressions fast</td>
</tr>
<tr class="even">
<td>Have rollback plan ready</td>
<td>Revert within minutes if needed</td>
</tr>
</tbody>
</table>
<hr>
</section>
</section>
<section id="summary-table" class="level2">
<h2 class="anchored" data-anchor-id="summary-table">Summary Table</h2>
<table class="caption-top table">
<colgroup>
<col style="width: 13%">
<col style="width: 30%">
<col style="width: 56%">
</colgroup>
<thead>
<tr class="header">
<th>#</th>
<th>Topic</th>
<th>Key Concept</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>1</td>
<td>REST API Design</td>
<td>Nouns for resources, proper HTTP methods/status codes, Pydantic validation</td>
</tr>
<tr class="even">
<td>2</td>
<td>Production Concurrency</td>
<td>Async workers + connection pooling + process pool for CPU work</td>
</tr>
<tr class="odd">
<td>3</td>
<td>Rate Limiting</td>
<td>Sliding window with Redis; per-IP/user/endpoint strategies</td>
</tr>
<tr class="even">
<td>4</td>
<td>Latency Optimization</td>
<td>Caching layers, N+1 elimination, indexes, pagination</td>
</tr>
<tr class="odd">
<td>5</td>
<td>Authentication</td>
<td>JWT + bcrypt + OAuth2; role-based authorization</td>
</tr>
<tr class="even">
<td>6</td>
<td>Security</td>
<td>Parameterized queries, input validation, CORS, security headers</td>
</tr>
<tr class="odd">
<td>7</td>
<td>Background Tasks</td>
<td>In-process for lightweight; task queues (arq/Celery) for heavy work</td>
</tr>
<tr class="even">
<td>8</td>
<td>API Versioning</td>
<td>URL-based versioning; additive changes are safe; deprecation headers</td>
</tr>
<tr class="odd">
<td>9</td>
<td>Observability</td>
<td>Health checks, Prometheus metrics, structured logging</td>
</tr>
<tr class="even">
<td>10</td>
<td>Graceful Shutdown</td>
<td>SIGTERM → stop accepting → drain → cleanup → exit</td>
</tr>
</tbody>
</table>
<hr>
</section>
<section id="whats-next" class="level2">
<h2 class="anchored" data-anchor-id="whats-next">What’s Next?</h2>
<p>This article covered production API concerns. For related content:</p>
<ul>
<li><strong>Python fundamentals:</strong> <a href="../../posts/swe-interview/Python-SWE-Interview-QA-1.html">Python SWE Interview QA - 1</a></li>
<li><strong>Advanced internals:</strong> <a href="../../posts/swe-interview/Python-SWE-Interview-QA-2.html">Python SWE Interview QA - 2</a></li>
<li><strong>Design patterns and structure:</strong> <a href="../../posts/swe-interview/Python-SWE-Interview-QA-3.html">Python SWE Interview QA - 3</a></li>
<li><strong>Machine learning concepts:</strong> <a href="../../posts/ml-interview/ML-Interview-QA-1.html">ML Interview QA - 1</a></li>
<li><strong>LLM architecture:</strong> <a href="../../posts/llm-interview/LLM-Interview-QA-1.html">LLM Interview QA - 1</a></li>
</ul>


</section>

 ]]></description>
  <guid>https://vectoringai.com/posts/swe-interview/Python-SWE-Interview-QA-4.html</guid>
  <pubDate>Thu, 21 May 2026 00:00:00 GMT</pubDate>
  <media:content url="https://vectoringai.com/images/python-swe-interview/thumb_python_swe_interview_qa_300.png" medium="image" type="image/png" height="96" width="144"/>
</item>
<item>
  <title>Python SWE Interview QA - 1</title>
  <dc:creator>Vectoring AI</dc:creator>
  <link>https://vectoringai.com/posts/swe-interview/Python-SWE-Interview-QA-1.html</link>
  <description><![CDATA[ 




<section id="introduction" class="level2">
<h2 class="anchored" data-anchor-id="introduction">Introduction</h2>
<p>This is <strong>Part 1</strong> of our Python SWE Interview QA series. It covers 10 foundational questions that appear in nearly every Python Software Engineer interview — from startups to FAANG. Each answer includes code examples, diagrams, and real-world context.</p>
<blockquote class="blockquote">
<p>This series complements our AI/ML interview preparation. For machine learning concepts, see <a href="../../posts/ml-interview/ML-Interview-QA-1.html">ML Interview QA - 1</a> and <a href="../../posts/ml-interview/ML-Interview-QA-2.html">ML Interview QA - 2</a>. For LLM topics, see <a href="../../posts/llm-interview/LLM-Interview-QA-1.html">LLM Interview QA - 1</a>.</p>
</blockquote>
<hr>
</section>
<section id="q1-what-is-the-difference-between-mutable-and-immutable-objects-in-python" class="level2">
<h2 class="anchored" data-anchor-id="q1-what-is-the-difference-between-mutable-and-immutable-objects-in-python">Q1: What is the difference between mutable and immutable objects in Python?</h2>
<p><strong>Answer:</strong></p>
<p>In Python, objects are either <strong>mutable</strong> (can be changed after creation) or <strong>immutable</strong> (cannot be changed after creation). This distinction affects how Python handles memory, function arguments, and hashability.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    subgraph Immutable["Immutable Objects"]
        I1["int: 42"]
        I2["float: 3.14"]
        I3["str: 'hello'"]
        I4["tuple: (1, 2, 3)"]
        I5["frozenset: frozenset({1,2})"]
        I6["bool: True"]
    end

    subgraph Mutable["Mutable Objects"]
        M1["list: [1, 2, 3]"]
        M2["dict: {'a': 1}"]
        M3["set: {1, 2, 3}"]
        M4["bytearray"]
        M5["Custom objects (default)"]
    end

    style Immutable fill:#56cc9d,stroke:#333,color:#fff
    style Mutable fill:#ffce67,stroke:#333
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="key-behavioral-differences" class="level3">
<h3 class="anchored" data-anchor-id="key-behavioral-differences">Key Behavioral Differences</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 28%">
<col style="width: 32%">
<col style="width: 39%">
</colgroup>
<thead>
<tr class="header">
<th>Aspect</th>
<th>Mutable</th>
<th>Immutable</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Modification</td>
<td>Changed in-place</td>
<td>New object created on “modification”</td>
</tr>
<tr class="even">
<td>Hashable?</td>
<td>No (can’t be dict keys)</td>
<td>Yes (can be dict keys/set members)</td>
</tr>
<tr class="odd">
<td>Thread safety</td>
<td>Needs synchronization</td>
<td>Inherently thread-safe</td>
</tr>
<tr class="even">
<td>Memory</td>
<td>Same id after modification</td>
<td>New id after any “change”</td>
</tr>
<tr class="odd">
<td>Function arguments</td>
<td>Changes visible to caller</td>
<td>Changes not visible to caller</td>
</tr>
</tbody>
</table>
</section>
<section id="code-example-the-critical-difference" class="level3">
<h3 class="anchored" data-anchor-id="code-example-the-critical-difference">Code Example: The Critical Difference</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Immutable: str</span></span>
<span id="cb1-2">s <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"hello"</span></span>
<span id="cb1-3">s_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">id</span>(s)</span>
<span id="cb1-4">s <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">" world"</span>       <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Creates a NEW string object</span></span>
<span id="cb1-5"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">id</span>(s) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> s_id)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># False — different object!</span></span>
<span id="cb1-6"></span>
<span id="cb1-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Mutable: list</span></span>
<span id="cb1-8">lst <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]</span>
<span id="cb1-9">lst_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">id</span>(lst)</span>
<span id="cb1-10">lst.append(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Modifies SAME object</span></span>
<span id="cb1-11"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">id</span>(lst) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> lst_id)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># True — same object!</span></span></code></pre></div></div>
</section>
<section id="why-this-matters-mutable-default-arguments-bug" class="level3">
<h3 class="anchored" data-anchor-id="why-this-matters-mutable-default-arguments-bug">Why This Matters: Mutable Default Arguments Bug</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># DANGEROUS: mutable default argument</span></span>
<span id="cb2-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> append_item(item, items<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[]):</span>
<span id="cb2-3">    items.append(item)</span>
<span id="cb2-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> items</span>
<span id="cb2-5"></span>
<span id="cb2-6"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(append_item(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># [1]</span></span>
<span id="cb2-7"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(append_item(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># [1, 2] — </span><span class="al" style="color: #AD0000;
background-color: null;
font-style: inherit;">BUG</span><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">! Expected [2]</span></span>
<span id="cb2-8"></span>
<span id="cb2-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># SAFE: use None as default</span></span>
<span id="cb2-10"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> append_item_safe(item, items<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>):</span>
<span id="cb2-11">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> items <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb2-12">        items <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb2-13">    items.append(item)</span>
<span id="cb2-14">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> items</span></code></pre></div></div>
</section>
<section id="real-world-impact" class="level3">
<h3 class="anchored" data-anchor-id="real-world-impact">Real-World Impact</h3>
<ul>
<li><strong>Dict keys:</strong> Only immutable objects can be dict keys (<code>tuple</code> yes, <code>list</code> no)</li>
<li><strong>Function caching:</strong> <code>@functools.lru_cache</code> only works with hashable (immutable) arguments</li>
<li><strong>Concurrent programming:</strong> Immutable objects are inherently thread-safe</li>
</ul>
<hr>
</section>
</section>
<section id="q2-what-is-the-global-interpreter-lock-gil-and-how-does-it-affect-concurrency" class="level2">
<h2 class="anchored" data-anchor-id="q2-what-is-the-global-interpreter-lock-gil-and-how-does-it-affect-concurrency">Q2: What is the Global Interpreter Lock (GIL) and how does it affect concurrency?</h2>
<p><strong>Answer:</strong></p>
<p>The <strong>GIL</strong> is a mutex in CPython that allows only <strong>one thread to execute Python bytecode at a time</strong>, even on multi-core machines. It exists to protect CPython’s memory management (reference counting) from race conditions.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    subgraph GIL_Effect["GIL: Only One Thread Executes at a Time"]
        T1["Thread 1: Running ✓"]
        T2["Thread 2: Waiting ✗"]
        T3["Thread 3: Waiting ✗"]
    end

    subgraph CPU["Multi-Core CPU"]
        C1["Core 1: Active"]
        C2["Core 2: Idle"]
        C3["Core 3: Idle"]
        C4["Core 4: Idle"]
    end

    GIL_Effect --&gt; CPU

    style GIL_Effect fill:#ff7851,stroke:#333,color:#fff
    style CPU fill:#ffce67,stroke:#333
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="impact-on-different-workloads" class="level3">
<h3 class="anchored" data-anchor-id="impact-on-different-workloads">Impact on Different Workloads</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 40%">
<col style="width: 45%">
<col style="width: 13%">
</colgroup>
<thead>
<tr class="header">
<th>Workload Type</th>
<th>Threading Helps?</th>
<th>Why</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>CPU-bound</strong> (math, processing)</td>
<td>No — GIL blocks parallelism</td>
<td>Only one thread computes at a time</td>
</tr>
<tr class="even">
<td><strong>I/O-bound</strong> (network, file, DB)</td>
<td>Yes — GIL released during I/O</td>
<td>Threads can wait concurrently</td>
</tr>
<tr class="odd">
<td><strong>C extensions</strong> (NumPy, Pandas)</td>
<td>Yes — GIL released in C code</td>
<td>Heavy computation happens outside GIL</td>
</tr>
</tbody>
</table>
</section>
<section id="solutions-for-cpu-bound-parallelism" class="level3">
<h3 class="anchored" data-anchor-id="solutions-for-cpu-bound-parallelism">Solutions for CPU-Bound Parallelism</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ✗ Threading — limited by GIL for CPU work</span></span>
<span id="cb3-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> threading</span>
<span id="cb3-3"></span>
<span id="cb3-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ✓ Multiprocessing — separate processes, separate GILs</span></span>
<span id="cb3-5"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> multiprocessing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Pool</span>
<span id="cb3-6"></span>
<span id="cb3-7"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> cpu_heavy(n):</span>
<span id="cb3-8">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> i <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(n))</span>
<span id="cb3-9"></span>
<span id="cb3-10"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> Pool(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> p:</span>
<span id="cb3-11">    results <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> p.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">map</span>(cpu_heavy, [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span>
<span id="cb3-12"></span>
<span id="cb3-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ✓ asyncio — for I/O-bound concurrency</span></span>
<span id="cb3-14"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> asyncio</span>
<span id="cb3-15"></span>
<span id="cb3-16"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> fetch_data(url):</span>
<span id="cb3-17">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> aiohttp.ClientSession() <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> session:</span>
<span id="cb3-18">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> session.get(url) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> resp:</span>
<span id="cb3-19">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> resp.json()</span></code></pre></div></div>
</section>
<section id="when-to-use-what" class="level3">
<h3 class="anchored" data-anchor-id="when-to-use-what">When to Use What</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 31%">
<col style="width: 31%">
<col style="width: 37%">
</colgroup>
<thead>
<tr class="header">
<th>Approach</th>
<th>Best For</th>
<th>GIL Impact</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>threading</code></td>
<td>I/O-bound (API calls, file I/O)</td>
<td>GIL released during I/O waits</td>
</tr>
<tr class="even">
<td><code>multiprocessing</code></td>
<td>CPU-bound (data processing)</td>
<td>Each process has own GIL</td>
</tr>
<tr class="odd">
<td><code>asyncio</code></td>
<td>Many concurrent I/O operations</td>
<td>Single thread, no GIL contention</td>
</tr>
<tr class="even">
<td>C extensions</td>
<td>Heavy numerical computation</td>
<td>Can release GIL explicitly</td>
</tr>
</tbody>
</table>
</section>
<section id="key-interview-point" class="level3">
<h3 class="anchored" data-anchor-id="key-interview-point">Key Interview Point</h3>
<p>Python 3.13+ introduced a <strong>free-threaded mode</strong> (PEP 703) that experimentally removes the GIL, enabling true multi-threaded parallelism. This is the biggest change to CPython’s concurrency model in its history.</p>
<hr>
</section>
</section>
<section id="q3-what-are-decorators-and-how-do-they-work" class="level2">
<h2 class="anchored" data-anchor-id="q3-what-are-decorators-and-how-do-they-work">Q3: What are decorators and how do they work?</h2>
<p><strong>Answer:</strong></p>
<p>A <strong>decorator</strong> is a function that takes another function as input and returns a modified version of it — adding behavior before/after without changing the original function’s code.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph LR
    ORIG["Original Function&lt;br/&gt;def greet(): ..."]
    DEC["Decorator&lt;br/&gt;@log_calls"]
    WRAPPED["Wrapped Function&lt;br/&gt;logging + greet() + logging"]

    ORIG --&gt; DEC --&gt; WRAPPED

    style ORIG fill:#6cc3d5,stroke:#333,color:#fff
    style DEC fill:#ffce67,stroke:#333
    style WRAPPED fill:#56cc9d,stroke:#333,color:#fff
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="how-decorators-work-under-the-hood" class="level3">
<h3 class="anchored" data-anchor-id="how-decorators-work-under-the-hood">How Decorators Work Under the Hood</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># This decorator syntax:</span></span>
<span id="cb4-2"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@my_decorator</span></span>
<span id="cb4-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> say_hello():</span>
<span id="cb4-4">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Hello!"</span>)</span>
<span id="cb4-5"></span>
<span id="cb4-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Is exactly equivalent to:</span></span>
<span id="cb4-7"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> say_hello():</span>
<span id="cb4-8">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Hello!"</span>)</span>
<span id="cb4-9">say_hello <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> my_decorator(say_hello)</span></code></pre></div></div>
</section>
<section id="writing-a-proper-decorator" class="level3">
<h3 class="anchored" data-anchor-id="writing-a-proper-decorator">Writing a Proper Decorator</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> functools</span>
<span id="cb5-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> time</span>
<span id="cb5-3"></span>
<span id="cb5-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> timer(func):</span>
<span id="cb5-5">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Decorator that measures execution time."""</span></span>
<span id="cb5-6">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@functools.wraps</span>(func)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Preserves original function metadata</span></span>
<span id="cb5-7">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> wrapper(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>args, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>kwargs):</span>
<span id="cb5-8">        start <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> time.perf_counter()</span>
<span id="cb5-9">        result <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> func(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>args, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>kwargs)</span>
<span id="cb5-10">        elapsed <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> time.perf_counter() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> start</span>
<span id="cb5-11">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>func<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">__name__</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> took </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>elapsed<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.4f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">s"</span>)</span>
<span id="cb5-12">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> result</span>
<span id="cb5-13">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> wrapper</span>
<span id="cb5-14"></span>
<span id="cb5-15"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@timer</span></span>
<span id="cb5-16"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> process_data(n):</span>
<span id="cb5-17">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Process n items."""</span></span>
<span id="cb5-18">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(n))</span>
<span id="cb5-19"></span>
<span id="cb5-20">process_data(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1_000_000</span>)</span>
<span id="cb5-21"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Output: process_data took 0.0312s</span></span>
<span id="cb5-22"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(process_data.<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">__name__</span>)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># "process_data" (preserved by @wraps)</span></span></code></pre></div></div>
</section>
<section id="decorators-with-arguments" class="level3">
<h3 class="anchored" data-anchor-id="decorators-with-arguments">Decorators with Arguments</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> retry(max_attempts<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, delay<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>):</span>
<span id="cb6-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Decorator that retries on failure."""</span></span>
<span id="cb6-3">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> decorator(func):</span>
<span id="cb6-4">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@functools.wraps</span>(func)</span>
<span id="cb6-5">        <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> wrapper(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>args, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>kwargs):</span>
<span id="cb6-6">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> attempt <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(max_attempts):</span>
<span id="cb6-7">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">try</span>:</span>
<span id="cb6-8">                    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> func(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>args, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>kwargs)</span>
<span id="cb6-9">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">except</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">Exception</span> <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> e:</span>
<span id="cb6-10">                    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> attempt <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> max_attempts <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>:</span>
<span id="cb6-11">                        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span></span>
<span id="cb6-12">                    time.sleep(delay)</span>
<span id="cb6-13">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> wrapper</span>
<span id="cb6-14">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> decorator</span>
<span id="cb6-15"></span>
<span id="cb6-16"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@retry</span>(max_attempts<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, delay<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb6-17"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> call_api(url):</span>
<span id="cb6-18">    ...</span></code></pre></div></div>
</section>
<section id="common-production-use-cases" class="level3">
<h3 class="anchored" data-anchor-id="common-production-use-cases">Common Production Use Cases</h3>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Use Case</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>Logging</strong></td>
<td><code>@log_calls</code> — log function entry/exit</td>
</tr>
<tr class="even">
<td><strong>Authentication</strong></td>
<td><code>@login_required</code> (Flask/Django)</td>
</tr>
<tr class="odd">
<td><strong>Caching</strong></td>
<td><code>@functools.lru_cache</code></td>
</tr>
<tr class="even">
<td><strong>Rate limiting</strong></td>
<td><code>@rate_limit(calls=10, period=60)</code></td>
</tr>
<tr class="odd">
<td><strong>Validation</strong></td>
<td><code>@validate_input</code> — check argument types</td>
</tr>
<tr class="even">
<td><strong>Timing</strong></td>
<td><code>@timer</code> — measure execution time</td>
</tr>
<tr class="odd">
<td><strong>Retry logic</strong></td>
<td><code>@retry(max_attempts=3)</code></td>
</tr>
</tbody>
</table>
<hr>
</section>
</section>
<section id="q4-what-are-generators-and-how-do-they-differ-from-regular-functions" class="level2">
<h2 class="anchored" data-anchor-id="q4-what-are-generators-and-how-do-they-differ-from-regular-functions">Q4: What are generators and how do they differ from regular functions?</h2>
<p><strong>Answer:</strong></p>
<p>A <strong>generator</strong> is a function that uses <code>yield</code> to produce a sequence of values lazily (one at a time), instead of computing and storing all values in memory at once.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph LR
    subgraph Regular["Regular Function"]
        RF1["Computes ALL results"]
        RF2["Stores in memory (list)"]
        RF3["Returns entire collection"]
    end

    subgraph Generator["Generator Function"]
        GF1["Computes ONE result at a time"]
        GF2["Suspends state between yields"]
        GF3["Resumes on next() call"]
    end

    style Regular fill:#ff7851,stroke:#333,color:#fff
    style Generator fill:#56cc9d,stroke:#333,color:#fff
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="key-differences" class="level3">
<h3 class="anchored" data-anchor-id="key-differences">Key Differences</h3>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Aspect</th>
<th>Regular Function</th>
<th>Generator</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Keyword</td>
<td><code>return</code></td>
<td><code>yield</code></td>
</tr>
<tr class="even">
<td>Execution</td>
<td>Runs to completion</td>
<td>Pauses at each <code>yield</code></td>
</tr>
<tr class="odd">
<td>Memory</td>
<td>All results in memory</td>
<td>One value at a time</td>
</tr>
<tr class="even">
<td>Returns</td>
<td>Value</td>
<td>Generator iterator</td>
</tr>
<tr class="odd">
<td>State</td>
<td>Lost after return</td>
<td>Preserved between yields</td>
</tr>
<tr class="even">
<td>Reusable</td>
<td>Call again</td>
<td>Must create new generator</td>
</tr>
</tbody>
</table>
</section>
<section id="code-example" class="level3">
<h3 class="anchored" data-anchor-id="code-example">Code Example</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Regular function: stores ALL values in memory</span></span>
<span id="cb7-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_squares_list(n):</span>
<span id="cb7-3">    result <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb7-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(n):</span>
<span id="cb7-5">        result.append(i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb7-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> result  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 1 billion items = ~8 GB RAM!</span></span>
<span id="cb7-7"></span>
<span id="cb7-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Generator: produces ONE value at a time</span></span>
<span id="cb7-9"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_squares_gen(n):</span>
<span id="cb7-10">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(n):</span>
<span id="cb7-11">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">yield</span> i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Pauses here, resumes on next()</span></span>
<span id="cb7-12"></span>
<span id="cb7-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Memory comparison</span></span>
<span id="cb7-14">squares_list <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_squares_list(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1_000_000_000</span>)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># MemoryError!</span></span>
<span id="cb7-15">squares_gen <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_squares_gen(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1_000_000_000</span>)     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Instant, ~0 bytes</span></span>
<span id="cb7-16"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">next</span>(squares_gen)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 0</span></span>
<span id="cb7-17"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">next</span>(squares_gen)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 1</span></span></code></pre></div></div>
</section>
<section id="generator-expressions-one-liners" class="level3">
<h3 class="anchored" data-anchor-id="generator-expressions-one-liners">Generator Expressions (One-liners)</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># List comprehension: creates full list in memory</span></span>
<span id="cb8-2">squares_list <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> x <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10_000_000</span>)]  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ~80 MB</span></span>
<span id="cb8-3"></span>
<span id="cb8-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Generator expression: lazy evaluation</span></span>
<span id="cb8-5">squares_gen <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> x <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10_000_000</span>))   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ~0 bytes</span></span></code></pre></div></div>
</section>
<section id="real-world-use-cases" class="level3">
<h3 class="anchored" data-anchor-id="real-world-use-cases">Real-World Use Cases</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 41%">
<col style="width: 58%">
</colgroup>
<thead>
<tr class="header">
<th>Use Case</th>
<th>Why Generator</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Reading large files</td>
<td>Process line by line without loading entire file</td>
</tr>
<tr class="even">
<td>Streaming data</td>
<td>Handle infinite/continuous data streams</td>
</tr>
<tr class="odd">
<td>Pipeline processing</td>
<td>Chain transformations without intermediate lists</td>
</tr>
<tr class="even">
<td>Database cursors</td>
<td>Fetch rows one at a time from large result sets</td>
</tr>
<tr class="odd">
<td>API pagination</td>
<td>Yield pages as they’re fetched</td>
</tr>
</tbody>
</table>
</section>
<section id="yield-from-delegating-to-sub-generators" class="level3">
<h3 class="anchored" data-anchor-id="yield-from-delegating-to-sub-generators"><code>yield from</code> — Delegating to Sub-generators</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> flatten(nested_list):</span>
<span id="cb9-2">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> item <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> nested_list:</span>
<span id="cb9-3">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">isinstance</span>(item, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>):</span>
<span id="cb9-4">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">yield</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">from</span> flatten(item)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Delegate to recursive generator</span></span>
<span id="cb9-5">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb9-6">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">yield</span> item</span>
<span id="cb9-7"></span>
<span id="cb9-8"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>(flatten([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>]], <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>]))  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># [1, 2, 3, 4, 5]</span></span></code></pre></div></div>
<hr>
</section>
</section>
<section id="q5-explain-pythons-data-model-__init__-__repr__-__eq__-and-dunder-methods." class="level2">
<h2 class="anchored" data-anchor-id="q5-explain-pythons-data-model-__init__-__repr__-__eq__-and-dunder-methods.">Q5: Explain Python’s data model: <code>__init__</code>, <code>__repr__</code>, <code>__eq__</code>, and dunder methods.</h2>
<p><strong>Answer:</strong></p>
<p>Python’s <strong>data model</strong> (dunder/magic methods) defines how objects behave with built-in operations. By implementing these methods, custom classes integrate seamlessly with Python’s syntax and built-in functions.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    DM["Python Data Model (Dunder Methods)"]
    DM --&gt; LIFE["Object Lifecycle"]
    DM --&gt; REP["Representation"]
    DM --&gt; COMP["Comparison"]
    DM --&gt; CONT["Container Protocol"]
    DM --&gt; MATH["Arithmetic"]
    DM --&gt; CTX["Context Manager"]

    LIFE --&gt; L1["__init__: Initialize"]
    LIFE --&gt; L2["__new__: Create"]
    LIFE --&gt; L3["__del__: Finalize"]

    REP --&gt; R1["__repr__: Developer string"]
    REP --&gt; R2["__str__: User string"]
    REP --&gt; R3["__format__: f-string"]

    COMP --&gt; C1["__eq__: =="]
    COMP --&gt; C2["__lt__: &lt;"]
    COMP --&gt; C3["__hash__: hash()"]

    CONT --&gt; CO1["__len__: len()"]
    CONT --&gt; CO2["__getitem__: obj[key]"]
    CONT --&gt; CO3["__iter__: for loop"]
    CONT --&gt; CO4["__contains__: in"]

    style DM fill:#56cc9d,stroke:#333,color:#fff
    style LIFE fill:#6cc3d5,stroke:#333,color:#fff
    style COMP fill:#ffce67,stroke:#333
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="essential-dunder-methods" class="level3">
<h3 class="anchored" data-anchor-id="essential-dunder-methods">Essential Dunder Methods</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> functools <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> total_ordering</span>
<span id="cb10-2"></span>
<span id="cb10-3"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@total_ordering</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Generates __le__, __gt__, __ge__ from __eq__ and __lt__</span></span>
<span id="cb10-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Money:</span>
<span id="cb10-5">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, amount, currency<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"USD"</span>):</span>
<span id="cb10-6">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.amount <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> amount</span>
<span id="cb10-7">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.currency <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> currency</span>
<span id="cb10-8"></span>
<span id="cb10-9">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__repr__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb10-10">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""For developers: unambiguous, ideally eval()-able."""</span></span>
<span id="cb10-11">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Money(</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>amount<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!r}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">, </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>currency<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!r}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">)"</span></span>
<span id="cb10-12"></span>
<span id="cb10-13">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__str__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb10-14">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""For users: readable."""</span></span>
<span id="cb10-15">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"$</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>amount<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.2f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>currency<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span></span>
<span id="cb10-16"></span>
<span id="cb10-17">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__eq__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, other):</span>
<span id="cb10-18">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">isinstance</span>(other, Money):</span>
<span id="cb10-19">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">NotImplemented</span></span>
<span id="cb10-20">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.amount <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> other.amount <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.currency <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> other.currency</span>
<span id="cb10-21"></span>
<span id="cb10-22">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__lt__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, other):</span>
<span id="cb10-23">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">isinstance</span>(other, Money):</span>
<span id="cb10-24">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">NotImplemented</span></span>
<span id="cb10-25">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.currency <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> other.currency:</span>
<span id="cb10-26">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">ValueError</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Cannot compare different currencies"</span>)</span>
<span id="cb10-27">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.amount <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> other.amount</span>
<span id="cb10-28"></span>
<span id="cb10-29">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__hash__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb10-30">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">hash</span>((<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.amount, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.currency))</span>
<span id="cb10-31"></span>
<span id="cb10-32">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__add__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, other):</span>
<span id="cb10-33">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">isinstance</span>(other, Money):</span>
<span id="cb10-34">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">NotImplemented</span></span>
<span id="cb10-35">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.currency <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> other.currency:</span>
<span id="cb10-36">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">ValueError</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Cannot add different currencies"</span>)</span>
<span id="cb10-37">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> Money(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.amount <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> other.amount, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.currency)</span>
<span id="cb10-38"></span>
<span id="cb10-39">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__bool__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb10-40">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.amount <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span></code></pre></div></div>
</section>
<section id="usage" class="level3">
<h3 class="anchored" data-anchor-id="usage">Usage</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1">wallet <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Money(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">50.00</span>)</span>
<span id="cb11-2">tip <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Money(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">10.00</span>)</span>
<span id="cb11-3"></span>
<span id="cb11-4"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">repr</span>(wallet))     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Money(50.0, 'USD')</span></span>
<span id="cb11-5"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>(wallet))      <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># $50.00 USD</span></span>
<span id="cb11-6"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(wallet <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> tip)     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># $60.00 USD</span></span>
<span id="cb11-7"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(wallet <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> tip)     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># True</span></span>
<span id="cb11-8"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(wallet <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> Money(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">50.0</span>))  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># True</span></span>
<span id="cb11-9"></span>
<span id="cb11-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Works as dict key (hashable)</span></span>
<span id="cb11-11">prices <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {Money(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">9.99</span>): <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"coffee"</span>, Money(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">24.99</span>): <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"book"</span>}</span></code></pre></div></div>
</section>
<section id="key-rules" class="level3">
<h3 class="anchored" data-anchor-id="key-rules">Key Rules</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 31%">
<col style="width: 68%">
</colgroup>
<thead>
<tr class="header">
<th>Rule</th>
<th>Explanation</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>__repr__</code> should be unambiguous</td>
<td>Ideally <code>eval(repr(obj))</code> recreates the object</td>
</tr>
<tr class="even">
<td><code>__eq__</code> implies <code>__hash__</code></td>
<td>If you define <code>__eq__</code>, define <code>__hash__</code> too (or set to None)</td>
</tr>
<tr class="odd">
<td>Return <code>NotImplemented</code></td>
<td>For operators with incompatible types (lets Python try reverse)</td>
</tr>
<tr class="even">
<td><code>@dataclass</code> automates this</td>
<td>Python 3.7+ dataclasses generate <code>__init__</code>, <code>__repr__</code>, <code>__eq__</code></td>
</tr>
</tbody>
</table>
<hr>
</section>
</section>
<section id="q6-what-is-the-difference-between-deepcopy-and-shallow-copy" class="level2">
<h2 class="anchored" data-anchor-id="q6-what-is-the-difference-between-deepcopy-and-shallow-copy">Q6: What is the difference between <code>deepcopy</code> and shallow copy?</h2>
<p><strong>Answer:</strong></p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    subgraph Original["Original Object"]
        O["outer list"]
        O --&gt; A["inner list [1, 2]"]
        O --&gt; B["inner list [3, 4]"]
    end

    subgraph Shallow["Shallow Copy"]
        S["new outer list"]
        S --&gt; A
        S --&gt; B
    end

    subgraph Deep["Deep Copy"]
        D["new outer list"]
        D --&gt; A2["new inner list [1, 2]"]
        D --&gt; B2["new inner list [3, 4]"]
    end

    style Original fill:#6cc3d5,stroke:#333,color:#fff
    style Shallow fill:#ffce67,stroke:#333
    style Deep fill:#56cc9d,stroke:#333,color:#fff
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="three-levels-of-copying" class="level3">
<h3 class="anchored" data-anchor-id="three-levels-of-copying">Three Levels of “Copying”</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 27%">
<col style="width: 32%">
<col style="width: 40%">
</colgroup>
<thead>
<tr class="header">
<th>Operation</th>
<th>What it does</th>
<th>Nested objects</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>Assignment</strong> (<code>b = a</code>)</td>
<td>New reference to SAME object</td>
<td>Shared — changes in <code>b</code> affect <code>a</code></td>
</tr>
<tr class="even">
<td><strong>Shallow copy</strong> (<code>copy.copy(a)</code>)</td>
<td>New outer object, references same inner objects</td>
<td>Shared — inner changes affect both</td>
</tr>
<tr class="odd">
<td><strong>Deep copy</strong> (<code>copy.deepcopy(a)</code>)</td>
<td>New everything recursively</td>
<td>Independent — fully separate</td>
</tr>
</tbody>
</table>
</section>
<section id="code-demonstration" class="level3">
<h3 class="anchored" data-anchor-id="code-demonstration">Code Demonstration</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> copy</span>
<span id="cb12-2"></span>
<span id="cb12-3">original <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>], [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>]]</span>
<span id="cb12-4"></span>
<span id="cb12-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Assignment: same object</span></span>
<span id="cb12-6">assigned <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> original</span>
<span id="cb12-7">assigned[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>][<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">99</span></span>
<span id="cb12-8"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(original[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>][<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 99 — both point to same object!</span></span>
<span id="cb12-9"></span>
<span id="cb12-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Shallow copy: new outer, shared inner</span></span>
<span id="cb12-11">original <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>], [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>]]</span>
<span id="cb12-12">shallow <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> copy.copy(original)</span>
<span id="cb12-13">shallow.append([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>])        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Only affects shallow (new outer)</span></span>
<span id="cb12-14">shallow[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>][<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">99</span>            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Affects BOTH (shared inner)</span></span>
<span id="cb12-15"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(original[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>][<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])         <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 99 — inner list is shared!</span></span>
<span id="cb12-16"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(original))          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 2 — outer list is independent</span></span>
<span id="cb12-17"></span>
<span id="cb12-18"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Deep copy: fully independent</span></span>
<span id="cb12-19">original <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>], [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>]]</span>
<span id="cb12-20">deep <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> copy.deepcopy(original)</span>
<span id="cb12-21">deep[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>][<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">99</span>               <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Only affects deep</span></span>
<span id="cb12-22"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(original[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>][<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])         <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 1 — completely independent</span></span></code></pre></div></div>
</section>
<section id="quick-shallow-copy-methods" class="level3">
<h3 class="anchored" data-anchor-id="quick-shallow-copy-methods">Quick Shallow Copy Methods</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># All of these create shallow copies:</span></span>
<span id="cb13-2">lst_copy <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> lst[:]              <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Slice</span></span>
<span id="cb13-3">lst_copy <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> lst.copy()          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># .copy() method</span></span>
<span id="cb13-4">lst_copy <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>(lst)           <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Constructor</span></span>
<span id="cb13-5">dict_copy <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>original_dict}  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Dict unpacking</span></span>
<span id="cb13-6">dict_copy <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>.copy()        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># .copy() method</span></span></code></pre></div></div>
</section>
<section id="when-to-use-what-1" class="level3">
<h3 class="anchored" data-anchor-id="when-to-use-what-1">When to Use What</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 68%">
<col style="width: 31%">
</colgroup>
<thead>
<tr class="header">
<th>Situation</th>
<th>Use</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Simple flat lists/dicts</td>
<td>Shallow copy (fast, sufficient)</td>
</tr>
<tr class="even">
<td>Nested structures you’ll modify</td>
<td>Deep copy (safe, slower)</td>
</tr>
<tr class="odd">
<td>Immutable content (tuples of ints)</td>
<td>Shallow copy (inner can’t change)</td>
</tr>
<tr class="even">
<td>Performance-critical code</td>
<td>Shallow copy (avoid deep copy overhead)</td>
</tr>
</tbody>
</table>
<hr>
</section>
</section>
<section id="q7-how-does-pythons-args-and-kwargs-work" class="level2">
<h2 class="anchored" data-anchor-id="q7-how-does-pythons-args-and-kwargs-work">Q7: How does Python’s <code>*args</code> and <code>**kwargs</code> work?</h2>
<p><strong>Answer:</strong></p>
<p><code>*args</code> and <code>**kwargs</code> allow functions to accept a <strong>variable number of arguments</strong>:</p>
<ul>
<li><code>*args</code> collects extra <strong>positional</strong> arguments into a <strong>tuple</strong></li>
<li><code>**kwargs</code> collects extra <strong>keyword</strong> arguments into a <strong>dict</strong></li>
</ul>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    CALL["function(1, 2, 3, name='Alice', age=30)"]
    CALL --&gt; POS["Positional: (1, 2, 3) → *args tuple"]
    CALL --&gt; KW["Keyword: {'name': 'Alice', 'age': 30} → **kwargs dict"]

    style CALL fill:#56cc9d,stroke:#333,color:#fff
    style POS fill:#6cc3d5,stroke:#333,color:#fff
    style KW fill:#ffce67,stroke:#333
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="function-parameter-order" class="level3">
<h3 class="anchored" data-anchor-id="function-parameter-order">Function Parameter Order</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb14-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> func(pos_only, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span>, normal, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>args, kw_only, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>kwargs):</span>
<span id="cb14-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Complete parameter order (Python 3.8+)"""</span></span>
<span id="cb14-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pass</span></span>
<span id="cb14-4"></span>
<span id="cb14-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Order: positional-only / normal / *args / keyword-only / **kwargs</span></span></code></pre></div></div>
</section>
<section id="practical-examples" class="level3">
<h3 class="anchored" data-anchor-id="practical-examples">Practical Examples</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb15-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Flexible logging function</span></span>
<span id="cb15-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> log(message, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>args, level<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"INFO"</span>, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>kwargs):</span>
<span id="cb15-3">    formatted <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> message.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">format</span>(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>args) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> args <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> message</span>
<span id="cb15-4">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"[</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>level<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">] </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>formatted<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>, kwargs <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> kwargs <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>)</span>
<span id="cb15-5"></span>
<span id="cb15-6">log(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"User </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{}</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;"> logged in from </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{}</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Alice"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"NYC"</span>, level<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"DEBUG"</span>)</span>
<span id="cb15-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># [DEBUG] User Alice logged in from NYC</span></span>
<span id="cb15-8"></span>
<span id="cb15-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Forwarding arguments (decorator pattern)</span></span>
<span id="cb15-10"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> decorator(func):</span>
<span id="cb15-11">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@functools.wraps</span>(func)</span>
<span id="cb15-12">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> wrapper(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>args, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>kwargs):</span>
<span id="cb15-13">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Calling </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>func<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">__name__</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb15-14">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> func(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>args, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>kwargs)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Forward everything</span></span>
<span id="cb15-15">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> wrapper</span>
<span id="cb15-16"></span>
<span id="cb15-17"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Unpacking in function calls</span></span>
<span id="cb15-18"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> greet(first, last, greeting<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Hello"</span>):</span>
<span id="cb15-19">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>greeting<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">, </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>first<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>last<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">!"</span></span>
<span id="cb15-20"></span>
<span id="cb15-21">args <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Alice"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Smith"</span>)</span>
<span id="cb15-22">kwargs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"greeting"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Hi"</span>}</span>
<span id="cb15-23">greet(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>args, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>kwargs)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># "Hi, Alice Smith!"</span></span></code></pre></div></div>
</section>
<section id="common-patterns" class="level3">
<h3 class="anchored" data-anchor-id="common-patterns">Common Patterns</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 47%">
<col style="width: 52%">
</colgroup>
<thead>
<tr class="header">
<th>Pattern</th>
<th>Use Case</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>def func(*args)</code></td>
<td>Accept any number of positional args</td>
</tr>
<tr class="even">
<td><code>def func(**kwargs)</code></td>
<td>Accept any keyword args (config dicts)</td>
</tr>
<tr class="odd">
<td><code>func(*list_var)</code></td>
<td>Unpack list into positional args</td>
</tr>
<tr class="even">
<td><code>func(**dict_var)</code></td>
<td>Unpack dict into keyword args</td>
</tr>
<tr class="odd">
<td><code>def wrapper(*args, **kwargs)</code></td>
<td>Forward all args (decorators, proxies)</td>
</tr>
<tr class="even">
<td><code>{**dict1, **dict2}</code></td>
<td>Merge dictionaries</td>
</tr>
</tbody>
</table>
<hr>
</section>
</section>
<section id="q8-what-are-context-managers-and-the-with-statement" class="level2">
<h2 class="anchored" data-anchor-id="q8-what-are-context-managers-and-the-with-statement">Q8: What are context managers and the <code>with</code> statement?</h2>
<p><strong>Answer:</strong></p>
<p>A <strong>context manager</strong> is an object that defines setup and cleanup actions for a block of code, ensuring resources are properly managed even if exceptions occur.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    WITH["with open('file.txt') as f:"]
    WITH --&gt; ENTER["__enter__() called&lt;br/&gt;• Open resource&lt;br/&gt;• Return value assigned to 'f'"]
    ENTER --&gt; BODY["Execute body&lt;br/&gt;• Read/write file&lt;br/&gt;• May raise exception"]
    BODY --&gt; EXIT["__exit__() called ALWAYS&lt;br/&gt;• Close resource&lt;br/&gt;• Handle exceptions"]

    style WITH fill:#56cc9d,stroke:#333,color:#fff
    style ENTER fill:#6cc3d5,stroke:#333,color:#fff
    style EXIT fill:#ffce67,stroke:#333
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="why-context-managers-matter" class="level3">
<h3 class="anchored" data-anchor-id="why-context-managers-matter">Why Context Managers Matter</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb16-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># WITHOUT context manager — resource leak if exception occurs!</span></span>
<span id="cb16-2">f <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data.txt"</span>)</span>
<span id="cb16-3"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">try</span>:</span>
<span id="cb16-4">    data <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> f.read()</span>
<span id="cb16-5">    process(data)     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># If this raises, file stays open!</span></span>
<span id="cb16-6"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">finally</span>:</span>
<span id="cb16-7">    f.close()</span>
<span id="cb16-8"></span>
<span id="cb16-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># WITH context manager — always cleaned up</span></span>
<span id="cb16-10"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data.txt"</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> f:</span>
<span id="cb16-11">    data <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> f.read()</span>
<span id="cb16-12">    process(data)     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># File closed even if exception raised</span></span></code></pre></div></div>
</section>
<section id="writing-custom-context-managers" class="level3">
<h3 class="anchored" data-anchor-id="writing-custom-context-managers">Writing Custom Context Managers</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb17-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Method 1: Class-based</span></span>
<span id="cb17-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> DatabaseConnection:</span>
<span id="cb17-3">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, connection_string):</span>
<span id="cb17-4">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.connection_string <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> connection_string</span>
<span id="cb17-5">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.conn <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span></span>
<span id="cb17-6"></span>
<span id="cb17-7">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__enter__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb17-8">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.conn <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">connect</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.connection_string)</span>
<span id="cb17-9">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.conn</span>
<span id="cb17-10"></span>
<span id="cb17-11">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__exit__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, exc_type, exc_val, exc_tb):</span>
<span id="cb17-12">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.conn.close()</span>
<span id="cb17-13">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Don't suppress exceptions</span></span>
<span id="cb17-14"></span>
<span id="cb17-15"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Method 2: contextlib (simpler for most cases)</span></span>
<span id="cb17-16"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> contextlib <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> contextmanager</span>
<span id="cb17-17"></span>
<span id="cb17-18"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@contextmanager</span></span>
<span id="cb17-19"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> timer(label):</span>
<span id="cb17-20">    start <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> time.perf_counter()</span>
<span id="cb17-21">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">try</span>:</span>
<span id="cb17-22">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">yield</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Code inside 'with' block runs here</span></span>
<span id="cb17-23">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">finally</span>:</span>
<span id="cb17-24">        elapsed <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> time.perf_counter() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> start</span>
<span id="cb17-25">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>label<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>elapsed<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.4f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">s"</span>)</span>
<span id="cb17-26"></span>
<span id="cb17-27"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> timer(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"data processing"</span>):</span>
<span id="cb17-28">    process_large_dataset()</span></code></pre></div></div>
</section>
<section id="common-built-in-context-managers" class="level3">
<h3 class="anchored" data-anchor-id="common-built-in-context-managers">Common Built-in Context Managers</h3>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Context Manager</th>
<th>Purpose</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>open(file)</code></td>
<td>File handling (auto-close)</td>
</tr>
<tr class="even">
<td><code>threading.Lock()</code></td>
<td>Thread synchronization</td>
</tr>
<tr class="odd">
<td><code>sqlite3.connect()</code></td>
<td>Database connection</td>
</tr>
<tr class="even">
<td><code>tempfile.TemporaryFile()</code></td>
<td>Auto-deleted temp files</td>
</tr>
<tr class="odd">
<td><code>contextlib.suppress(Exception)</code></td>
<td>Ignore specific exceptions</td>
</tr>
<tr class="even">
<td><code>decimal.localcontext()</code></td>
<td>Temporary decimal precision</td>
</tr>
</tbody>
</table>
<hr>
</section>
</section>
<section id="q9-how-does-python-handle-memory-management-and-garbage-collection" class="level2">
<h2 class="anchored" data-anchor-id="q9-how-does-python-handle-memory-management-and-garbage-collection">Q9: How does Python handle memory management and garbage collection?</h2>
<p><strong>Answer:</strong></p>
<p>Python uses a combination of <strong>reference counting</strong> (primary) and <strong>cyclic garbage collection</strong> (secondary) to manage memory automatically.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    MM["Python Memory Management"]
    MM --&gt; RC["Reference Counting&lt;br/&gt;(Primary mechanism)"]
    MM --&gt; GC["Cyclic Garbage Collector&lt;br/&gt;(Handles reference cycles)"]
    MM --&gt; POOL["Memory Pools&lt;br/&gt;(Small object optimization)"]

    RC --&gt; RC1["Every object has a count&lt;br/&gt;of references pointing to it"]
    RC --&gt; RC2["Count reaches 0 →&lt;br/&gt;immediately deallocated"]

    GC --&gt; GC1["Detects reference cycles&lt;br/&gt;(A → B → A)"]
    GC --&gt; GC2["Generational collection&lt;br/&gt;(Gen 0, 1, 2)"]

    POOL --&gt; P1["Objects &lt; 512 bytes&lt;br/&gt;use memory pools"]
    POOL --&gt; P2["Integer caching&lt;br/&gt;(-5 to 256 pre-allocated)"]

    style MM fill:#56cc9d,stroke:#333,color:#fff
    style RC fill:#6cc3d5,stroke:#333,color:#fff
    style GC fill:#ffce67,stroke:#333
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="reference-counting" class="level3">
<h3 class="anchored" data-anchor-id="reference-counting">Reference Counting</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb18-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> sys</span>
<span id="cb18-2"></span>
<span id="cb18-3">a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]         <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># refcount = 1</span></span>
<span id="cb18-4">b <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> a                  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># refcount = 2</span></span>
<span id="cb18-5"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(sys.getrefcount(a))  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 3 (includes temporary ref from getrefcount)</span></span>
<span id="cb18-6"></span>
<span id="cb18-7"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">del</span> b                  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># refcount drops to 1</span></span>
<span id="cb18-8"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">del</span> a                  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># refcount drops to 0 → immediately freed</span></span></code></pre></div></div>
</section>
<section id="the-cyclic-reference-problem" class="level3">
<h3 class="anchored" data-anchor-id="the-cyclic-reference-problem">The Cyclic Reference Problem</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb19-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Reference counting alone can't handle this:</span></span>
<span id="cb19-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Node:</span>
<span id="cb19-3">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb19-4">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.ref <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span></span>
<span id="cb19-5"></span>
<span id="cb19-6">a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Node()</span>
<span id="cb19-7">b <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Node()</span>
<span id="cb19-8">a.ref <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> b    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># a → b</span></span>
<span id="cb19-9">b.ref <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> a    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># b → a (cycle!)</span></span>
<span id="cb19-10"></span>
<span id="cb19-11"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">del</span> a, b     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># refcount never reaches 0!</span></span>
<span id="cb19-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Cyclic GC detects and collects these</span></span></code></pre></div></div>
</section>
<section id="generational-garbage-collection" class="level3">
<h3 class="anchored" data-anchor-id="generational-garbage-collection">Generational Garbage Collection</h3>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Generation</th>
<th>Contains</th>
<th>Collected</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Gen 0</td>
<td>Newly created objects</td>
<td>Most frequently</td>
</tr>
<tr class="even">
<td>Gen 1</td>
<td>Survived one collection</td>
<td>Less frequently</td>
</tr>
<tr class="odd">
<td>Gen 2</td>
<td>Long-lived objects</td>
<td>Rarely</td>
</tr>
</tbody>
</table>
</section>
<section id="practical-tips" class="level3">
<h3 class="anchored" data-anchor-id="practical-tips">Practical Tips</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb20" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb20-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> gc</span>
<span id="cb20-2"></span>
<span id="cb20-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Force garbage collection (rarely needed)</span></span>
<span id="cb20-4">gc.collect()</span>
<span id="cb20-5"></span>
<span id="cb20-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Disable GC for performance-critical sections</span></span>
<span id="cb20-7">gc.disable()</span>
<span id="cb20-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ... time-critical code ...</span></span>
<span id="cb20-9">gc.enable()</span>
<span id="cb20-10"></span>
<span id="cb20-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Avoid reference cycles with weak references</span></span>
<span id="cb20-12"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> weakref</span>
<span id="cb20-13">cache <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> weakref.WeakValueDictionary()</span></code></pre></div></div>
<hr>
</section>
</section>
<section id="q10-what-are-list-comprehensions-and-when-should-you-use-them-vs.-alternatives" class="level2">
<h2 class="anchored" data-anchor-id="q10-what-are-list-comprehensions-and-when-should-you-use-them-vs.-alternatives">Q10: What are list comprehensions, and when should you use them vs.&nbsp;alternatives?</h2>
<p><strong>Answer:</strong></p>
<p><strong>List comprehensions</strong> are concise, readable one-line expressions for creating lists. They’re faster than equivalent <code>for</code> loops because they’re optimized at the bytecode level.</p>
<section id="syntax" class="level3">
<h3 class="anchored" data-anchor-id="syntax">Syntax</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb21-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Basic: [expression for item in iterable]</span></span>
<span id="cb21-2">squares <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> x <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)]</span>
<span id="cb21-3"></span>
<span id="cb21-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># With condition: [expression for item in iterable if condition]</span></span>
<span id="cb21-5">evens <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [x <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> x <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb21-6"></span>
<span id="cb21-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Nested: [expression for item1 in iter1 for item2 in iter2]</span></span>
<span id="cb21-8">pairs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [(x, y) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> x <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> y <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> y]</span></code></pre></div></div>
</section>
<section id="comprehension-types" class="level3">
<h3 class="anchored" data-anchor-id="comprehension-types">Comprehension Types</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb22" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb22-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># List comprehension</span></span>
<span id="cb22-2">squares <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> x <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)]           <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># → list</span></span>
<span id="cb22-3"></span>
<span id="cb22-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Dict comprehension</span></span>
<span id="cb22-5">word_len <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {w: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(w) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> w <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> words}          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># → dict</span></span>
<span id="cb22-6"></span>
<span id="cb22-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Set comprehension</span></span>
<span id="cb22-8">unique_lower <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {s.lower() <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> s <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> names}      <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># → set</span></span>
<span id="cb22-9"></span>
<span id="cb22-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Generator expression (lazy!)</span></span>
<span id="cb22-11">sum_squares <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(x<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> x <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span>))  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># → generator (no memory!)</span></span></code></pre></div></div>
</section>
<section id="when-to-use-vs.-alternatives" class="level3">
<h3 class="anchored" data-anchor-id="when-to-use-vs.-alternatives">When to Use vs.&nbsp;Alternatives</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 34%">
<col style="width: 34%">
<col style="width: 31%">
</colgroup>
<thead>
<tr class="header">
<th>Approach</th>
<th>Use When</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>List comprehension</strong></td>
<td>Simple transform/filter, result needed as list</td>
<td><code>[x*2 for x in nums if x &gt; 0]</code></td>
</tr>
<tr class="even">
<td><strong>Generator expression</strong></td>
<td>Large data, only iterating once</td>
<td><code>sum(x*2 for x in nums)</code></td>
</tr>
<tr class="odd">
<td><strong><code>map()</code> + <code>filter()</code></strong></td>
<td>Already have named functions</td>
<td><code>map(str.upper, words)</code></td>
</tr>
<tr class="even">
<td><strong>For loop</strong></td>
<td>Complex logic, side effects, multiple statements</td>
<td>Multi-step processing</td>
</tr>
</tbody>
</table>
</section>
<section id="performance-comparison" class="level3">
<h3 class="anchored" data-anchor-id="performance-comparison">Performance Comparison</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb23" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb23-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> timeit</span>
<span id="cb23-2"></span>
<span id="cb23-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># List comprehension: ~30% faster than loop</span></span>
<span id="cb23-4">timeit.timeit(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'[x**2 for x in range(1000)]'</span>, number<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10000</span>)</span>
<span id="cb23-5"></span>
<span id="cb23-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Equivalent for loop</span></span>
<span id="cb23-7">timeit.timeit(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'''</span></span>
<span id="cb23-8"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">result = []</span></span>
<span id="cb23-9"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">for x in range(1000):</span></span>
<span id="cb23-10"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">    result.append(x**2)</span></span>
<span id="cb23-11"><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'''</span>, number<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10000</span>)</span></code></pre></div></div>
</section>
<section id="anti-pattern-over-complex-comprehensions" class="level3">
<h3 class="anchored" data-anchor-id="anti-pattern-over-complex-comprehensions">Anti-Pattern: Over-Complex Comprehensions</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb24" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb24-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># TOO COMPLEX — use a regular loop instead</span></span>
<span id="cb24-2">result <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [</span>
<span id="cb24-3">    transform(x)</span>
<span id="cb24-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> group <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> data</span>
<span id="cb24-5">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> x <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> group.items</span>
<span id="cb24-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> x.is_valid()</span>
<span id="cb24-7">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> x.score <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> threshold</span>
<span id="cb24-8">]</span>
<span id="cb24-9"></span>
<span id="cb24-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># BETTER — readable for loop</span></span>
<span id="cb24-11">result <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb24-12"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> group <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> data:</span>
<span id="cb24-13">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> x <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> group.items:</span>
<span id="cb24-14">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> x.is_valid() <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> x.score <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> threshold:</span>
<span id="cb24-15">            result.append(transform(x))</span></code></pre></div></div>
</section>
<section id="rule-of-thumb" class="level3">
<h3 class="anchored" data-anchor-id="rule-of-thumb">Rule of Thumb</h3>
<p>If a comprehension <strong>doesn’t fit on one line</strong> or requires <strong>mental effort to parse</strong>, use a regular <code>for</code> loop. Readability beats cleverness.</p>
<hr>
</section>
</section>
<section id="summary-table" class="level2">
<h2 class="anchored" data-anchor-id="summary-table">Summary Table</h2>
<table class="caption-top table">
<colgroup>
<col style="width: 13%">
<col style="width: 30%">
<col style="width: 56%">
</colgroup>
<thead>
<tr class="header">
<th>#</th>
<th>Topic</th>
<th>Key Concept</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>1</td>
<td>Mutable vs Immutable</td>
<td>Lists/dicts mutable; strings/tuples immutable. Affects hashability and function args</td>
</tr>
<tr class="even">
<td>2</td>
<td>GIL</td>
<td>Allows one thread at a time; use multiprocessing for CPU-bound parallelism</td>
</tr>
<tr class="odd">
<td>3</td>
<td>Decorators</td>
<td>Functions that wrap other functions; <code>@functools.wraps</code> preserves metadata</td>
</tr>
<tr class="even">
<td>4</td>
<td>Generators</td>
<td><code>yield</code> for lazy evaluation; memory-efficient for large datasets</td>
</tr>
<tr class="odd">
<td>5</td>
<td>Data Model</td>
<td>Dunder methods (<code>__repr__</code>, <code>__eq__</code>, etc.) define object behavior</td>
</tr>
<tr class="even">
<td>6</td>
<td>Shallow vs Deep Copy</td>
<td>Shallow shares inner objects; deep copies everything recursively</td>
</tr>
<tr class="odd">
<td>7</td>
<td><code>*args</code> / <code>**kwargs</code></td>
<td>Variable positional (tuple) and keyword (dict) arguments</td>
</tr>
<tr class="even">
<td>8</td>
<td>Context Managers</td>
<td><code>with</code> statement ensures cleanup; <code>__enter__</code> / <code>__exit__</code></td>
</tr>
<tr class="odd">
<td>9</td>
<td>Memory Management</td>
<td>Reference counting + cyclic GC; generational collection</td>
</tr>
<tr class="even">
<td>10</td>
<td>List Comprehensions</td>
<td>Fast, readable one-liners; use generator expressions for large data</td>
</tr>
</tbody>
</table>
<hr>
</section>
<section id="whats-next" class="level2">
<h2 class="anchored" data-anchor-id="whats-next">What’s Next?</h2>
<p>This article covered foundational Python concepts for SWE interviews. For related content:</p>
<ul>
<li><strong>Machine learning fundamentals:</strong> <a href="../../posts/ml-interview/ML-Interview-QA-1.html">ML Interview QA - 1</a></li>
<li><strong>Evaluation metrics and data handling:</strong> <a href="../../posts/ml-interview/ML-Interview-QA-2.html">ML Interview QA - 2</a></li>
<li><strong>LLM concepts for AI engineers:</strong> <a href="../../posts/llm-interview/LLM-Interview-QA-1.html">LLM Interview QA - 1</a></li>
<li><strong>Advanced LLM topics:</strong> <a href="../../posts/llm-interview/LLM-Interview-QA-2.html">LLM Interview QA - 2</a></li>
<li><strong>LLM configuration and decoding:</strong> <a href="../../posts/llm-interview/LLM-Interview-QA-3.html">LLM Interview QA - 3</a></li>
</ul>


</section>

 ]]></description>
  <guid>https://vectoringai.com/posts/swe-interview/Python-SWE-Interview-QA-1.html</guid>
  <pubDate>Wed, 20 May 2026 00:00:00 GMT</pubDate>
  <media:content url="https://vectoringai.com/images/python-swe-interview/thumb_python_swe_interview_qa_300.png" medium="image" type="image/png" height="96" width="144"/>
</item>
<item>
  <title>Python SWE Interview QA - 2</title>
  <dc:creator>Vectoring AI</dc:creator>
  <link>https://vectoringai.com/posts/swe-interview/Python-SWE-Interview-QA-2.html</link>
  <description><![CDATA[ 




<section id="introduction" class="level2">
<h2 class="anchored" data-anchor-id="introduction">Introduction</h2>
<p>This is <strong>Part 2</strong> of our Python SWE Interview QA series, covering <strong>advanced topics</strong> that distinguish senior engineers from junior candidates. These questions test deeper understanding of Python internals, modern Python features, and production-quality code practices.</p>
<blockquote class="blockquote">
<p>For foundational Python topics (GIL, decorators, generators, etc.), see <a href="../../posts/python-swe-interview/Python-SWE-Interview-QA-1.html">Python SWE Interview QA - 1</a>. For ML/AI interview content, see <a href="../../posts/ml-interview/ML-Interview-QA-1.html">ML Interview QA - 1</a> and <a href="../../posts/llm-interview/LLM-Interview-QA-1.html">LLM Interview QA - 1</a>.</p>
</blockquote>
<hr>
</section>
<section id="q1-how-does-asyncawait-work-in-python-and-when-should-you-use-it" class="level2">
<h2 class="anchored" data-anchor-id="q1-how-does-asyncawait-work-in-python-and-when-should-you-use-it">Q1: How does <code>async</code>/<code>await</code> work in Python and when should you use it?</h2>
<p><strong>Answer:</strong></p>
<p><code>async</code>/<code>await</code> is Python’s syntax for <strong>cooperative multitasking</strong> — it allows writing concurrent code that handles many I/O operations simultaneously within a single thread using an event loop.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    EL["Event Loop"]
    EL --&gt; T1["Task 1: await fetch(url1)"]
    EL --&gt; T2["Task 2: await fetch(url2)"]
    EL --&gt; T3["Task 3: await fetch(url3)"]

    T1 --&gt;|"suspended while waiting"| EL
    T2 --&gt;|"suspended while waiting"| EL
    T3 --&gt;|"suspended while waiting"| EL

    subgraph Timeline["Execution Timeline"]
        direction LR
        S1["Start T1"] --&gt; W1["T1 waits (I/O)"]
        W1 --&gt; S2["Start T2"]
        S2 --&gt; W2["T2 waits (I/O)"]
        W2 --&gt; S3["Start T3"]
        S3 --&gt; R1["T1 resumes"]
        R1 --&gt; R2["T2 resumes"]
        R2 --&gt; R3["T3 resumes"]
    end

    style EL fill:#56cc9d,stroke:#333,color:#fff
    style Timeline fill:#6cc3d5,stroke:#333,color:#fff
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="key-concepts" class="level3">
<h3 class="anchored" data-anchor-id="key-concepts">Key Concepts</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 40%">
<col style="width: 59%">
</colgroup>
<thead>
<tr class="header">
<th>Concept</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>async def</code></td>
<td>Declares a <strong>coroutine</strong> function</td>
</tr>
<tr class="even">
<td><code>await</code></td>
<td>Suspends execution until the awaited coroutine completes</td>
</tr>
<tr class="odd">
<td>Event Loop</td>
<td>Schedules and runs coroutines; switches between them at <code>await</code> points</td>
</tr>
<tr class="even">
<td><code>asyncio.gather()</code></td>
<td>Runs multiple coroutines concurrently</td>
</tr>
<tr class="odd">
<td><code>asyncio.create_task()</code></td>
<td>Schedules a coroutine to run in the background</td>
</tr>
</tbody>
</table>
</section>
<section id="practical-example" class="level3">
<h3 class="anchored" data-anchor-id="practical-example">Practical Example</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> asyncio</span>
<span id="cb1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> aiohttp</span>
<span id="cb1-3"></span>
<span id="cb1-4"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> fetch_url(session, url):</span>
<span id="cb1-5">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Fetch a single URL — suspends at await, frees event loop."""</span></span>
<span id="cb1-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> session.get(url) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> response:</span>
<span id="cb1-7">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> response.text()</span>
<span id="cb1-8"></span>
<span id="cb1-9"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> fetch_all(urls):</span>
<span id="cb1-10">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Fetch all URLs concurrently — not sequentially!"""</span></span>
<span id="cb1-11">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> aiohttp.ClientSession() <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> session:</span>
<span id="cb1-12">        tasks <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [asyncio.create_task(fetch_url(session, url)) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> url <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> urls]</span>
<span id="cb1-13">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> asyncio.gather(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>tasks)</span>
<span id="cb1-14"></span>
<span id="cb1-15"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Sequential: 10 URLs × 200ms = ~2000ms</span></span>
<span id="cb1-16"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Concurrent: 10 URLs overlapped = ~200ms</span></span>
<span id="cb1-17">urls <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"https://api.example.com/data/</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>i<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)]</span>
<span id="cb1-18">results <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> asyncio.run(fetch_all(urls))</span></code></pre></div></div>
</section>
<section id="when-to-use-and-not-use-async" class="level3">
<h3 class="anchored" data-anchor-id="when-to-use-and-not-use-async">When to Use (and NOT Use) async</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 43%">
<col style="width: 56%">
</colgroup>
<thead>
<tr class="header">
<th>Use async/await</th>
<th>Don’t use async/await</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Many network requests (APIs, web scraping)</td>
<td>CPU-heavy computation</td>
</tr>
<tr class="even">
<td>Database queries (async drivers)</td>
<td>Simple scripts with one I/O call</td>
</tr>
<tr class="odd">
<td>WebSocket servers</td>
<td>File I/O on local NVMe (already fast)</td>
</tr>
<tr class="even">
<td>Chat applications, real-time feeds</td>
<td>When libraries don’t support async</td>
</tr>
</tbody>
</table>
</section>
<section id="common-pitfalls" class="level3">
<h3 class="anchored" data-anchor-id="common-pitfalls">Common Pitfalls</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># WRONG: Calling coroutine without await</span></span>
<span id="cb2-2">result <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fetch_url(session, url)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Returns coroutine object, not result!</span></span>
<span id="cb2-3"></span>
<span id="cb2-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># WRONG: Sequential awaits when concurrency is possible</span></span>
<span id="cb2-5"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> url <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> urls:</span>
<span id="cb2-6">    result <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> fetch_url(session, url)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># One at a time!</span></span>
<span id="cb2-7"></span>
<span id="cb2-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># RIGHT: Concurrent execution</span></span>
<span id="cb2-9">results <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> asyncio.gather(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>[fetch_url(session, url) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> url <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> urls])</span>
<span id="cb2-10"></span>
<span id="cb2-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># WRONG: Blocking call inside async function</span></span>
<span id="cb2-12"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> bad():</span>
<span id="cb2-13">    time.sleep(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Blocks entire event loop!</span></span>
<span id="cb2-14"></span>
<span id="cb2-15"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># RIGHT: Use async sleep</span></span>
<span id="cb2-16"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> good():</span>
<span id="cb2-17">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> asyncio.sleep(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Yields control to event loop</span></span></code></pre></div></div>
<hr>
</section>
</section>
<section id="q2-what-are-type-hints-and-how-do-they-improve-python-code" class="level2">
<h2 class="anchored" data-anchor-id="q2-what-are-type-hints-and-how-do-they-improve-python-code">Q2: What are type hints and how do they improve Python code?</h2>
<p><strong>Answer:</strong></p>
<p><strong>Type hints</strong> (PEP 484+) are optional annotations that declare expected types for variables, function parameters, and return values. They don’t affect runtime behavior but enable <strong>static analysis</strong>, better IDE support, and self-documenting code.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph LR
    CODE["Type-Annotated Code"]
    CODE --&gt; MYPY["mypy / pyright&lt;br/&gt;Static type checker"]
    CODE --&gt; IDE["IDE&lt;br/&gt;Autocompletion + errors"]
    CODE --&gt; DOC["Documentation&lt;br/&gt;Self-documenting API"]

    MYPY --&gt; BUGS["Catches bugs&lt;br/&gt;before runtime"]
    IDE --&gt; PROD["Faster development"]
    DOC --&gt; MAINT["Easier maintenance"]

    style CODE fill:#56cc9d,stroke:#333,color:#fff
    style MYPY fill:#ff7851,stroke:#333,color:#fff
    style IDE fill:#6cc3d5,stroke:#333,color:#fff
    style DOC fill:#ffce67,stroke:#333
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="modern-type-hint-syntax-python-3.10" class="level3">
<h3 class="anchored" data-anchor-id="modern-type-hint-syntax-python-3.10">Modern Type Hint Syntax (Python 3.10+)</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Basic types</span></span>
<span id="cb3-2">name: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Alice"</span></span>
<span id="cb3-3">age: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span></span>
<span id="cb3-4">scores: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">98.5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">87.3</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">92.1</span>]</span>
<span id="cb3-5"></span>
<span id="cb3-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Union types (Python 3.10+: use |)</span></span>
<span id="cb3-7"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> find_user(user_id: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb3-8">    ...</span>
<span id="cb3-9"></span>
<span id="cb3-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Function signatures</span></span>
<span id="cb3-11"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> process_items(</span>
<span id="cb3-12">    items: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>],</span>
<span id="cb3-13">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>,</span>
<span id="cb3-14">    batch_size: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">32</span>,</span>
<span id="cb3-15">    callback: Callable[[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>], <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bool</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>,</span>
<span id="cb3-16">) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>]:</span>
<span id="cb3-17">    ...</span>
<span id="cb3-18"></span>
<span id="cb3-19"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Generics</span></span>
<span id="cb3-20"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> typing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> TypeVar, Generic</span>
<span id="cb3-21"></span>
<span id="cb3-22">T <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> TypeVar(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"T"</span>)</span>
<span id="cb3-23"></span>
<span id="cb3-24"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Stack(Generic[T]):</span>
<span id="cb3-25">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb3-26">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._items: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>[T] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb3-27"></span>
<span id="cb3-28">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> push(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, item: T) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb3-29">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._items.append(item)</span>
<span id="cb3-30"></span>
<span id="cb3-31">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> pop(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> T:</span>
<span id="cb3-32">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._items.pop()</span>
<span id="cb3-33"></span>
<span id="cb3-34"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Usage</span></span>
<span id="cb3-35">int_stack: Stack[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Stack()</span>
<span id="cb3-36">int_stack.push(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">42</span>)</span></code></pre></div></div>
</section>
<section id="advanced-type-features" class="level3">
<h3 class="anchored" data-anchor-id="advanced-type-features">Advanced Type Features</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> typing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Protocol, TypedDict, Literal, TypeGuard</span>
<span id="cb4-2"></span>
<span id="cb4-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Protocol: structural subtyping (duck typing with types)</span></span>
<span id="cb4-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Drawable(Protocol):</span>
<span id="cb4-5">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> draw(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>: ...</span>
<span id="cb4-6"></span>
<span id="cb4-7"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> render(obj: Drawable) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb4-8">    obj.draw()  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Any object with draw() method works</span></span>
<span id="cb4-9"></span>
<span id="cb4-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># TypedDict: typed dictionaries</span></span>
<span id="cb4-11"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> UserDict(TypedDict):</span>
<span id="cb4-12">    name: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span></span>
<span id="cb4-13">    age: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span></span>
<span id="cb4-14">    email: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span></span>
<span id="cb4-15"></span>
<span id="cb4-16"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Literal: restrict to specific values</span></span>
<span id="cb4-17"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> set_mode(mode: Literal[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"read"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"write"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"append"</span>]) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>: ...</span>
<span id="cb4-18"></span>
<span id="cb4-19"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># TypeGuard: narrow types in conditionals</span></span>
<span id="cb4-20"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> is_string_list(val: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">object</span>]) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> TypeGuard[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>]]:</span>
<span id="cb4-21">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">all</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">isinstance</span>(x, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> x <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> val)</span></code></pre></div></div>
</section>
<section id="type-hints-in-production" class="level3">
<h3 class="anchored" data-anchor-id="type-hints-in-production">Type Hints in Production</h3>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Tool</th>
<th>Purpose</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>mypy</code></td>
<td>Industry-standard static type checker</td>
</tr>
<tr class="even">
<td><code>pyright</code></td>
<td>Fast type checker (powers Pylance in VS Code)</td>
</tr>
<tr class="odd">
<td><code>pydantic</code></td>
<td>Runtime type validation (APIs, configs)</td>
</tr>
<tr class="even">
<td><code>beartype</code></td>
<td>Lightweight runtime type checking decorator</td>
</tr>
</tbody>
</table>
<hr>
</section>
</section>
<section id="q3-what-are-dataclasses-and-when-should-you-use-them-vs.-regular-classes" class="level2">
<h2 class="anchored" data-anchor-id="q3-what-are-dataclasses-and-when-should-you-use-them-vs.-regular-classes">Q3: What are <code>dataclasses</code> and when should you use them vs.&nbsp;regular classes?</h2>
<p><strong>Answer:</strong></p>
<p><code>dataclasses</code> (Python 3.7+) automatically generate <code>__init__</code>, <code>__repr__</code>, <code>__eq__</code>, and other boilerplate methods for classes that primarily store data.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    subgraph Regular["Regular Class (Manual)"]
        R1["Write __init__"]
        R2["Write __repr__"]
        R3["Write __eq__"]
        R4["Write __hash__"]
        R5["~30 lines of boilerplate"]
    end

    subgraph DC["@dataclass (Auto-generated)"]
        D1["@dataclass decorator"]
        D2["Just define fields"]
        D3["Everything generated"]
        D4["~5 lines total"]
    end

    style Regular fill:#ff7851,stroke:#333,color:#fff
    style DC fill:#56cc9d,stroke:#333,color:#fff
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="comparison-before-vs-after" class="level3">
<h3 class="anchored" data-anchor-id="comparison-before-vs-after">Comparison: Before vs After</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># WITHOUT dataclass: ~25 lines of boilerplate</span></span>
<span id="cb5-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> PointManual:</span>
<span id="cb5-3">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, x: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>, y: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>, label: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>):</span>
<span id="cb5-4">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> x</span>
<span id="cb5-5">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y</span>
<span id="cb5-6">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.label <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> label</span>
<span id="cb5-7"></span>
<span id="cb5-8">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__repr__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb5-9">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"PointManual(x=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>x<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!r}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">, y=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>y<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!r}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">, label=</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>label<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!r}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">)"</span></span>
<span id="cb5-10"></span>
<span id="cb5-11">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__eq__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, other):</span>
<span id="cb5-12">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">isinstance</span>(other, PointManual):</span>
<span id="cb5-13">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">NotImplemented</span></span>
<span id="cb5-14">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> (<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.x, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.label) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> (other.x, other.y, other.label)</span>
<span id="cb5-15"></span>
<span id="cb5-16">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__hash__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb5-17">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">hash</span>((<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.x, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.label))</span>
<span id="cb5-18"></span>
<span id="cb5-19"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># WITH dataclass: 5 lines, same functionality</span></span>
<span id="cb5-20"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> dataclasses <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> dataclass, field</span>
<span id="cb5-21"></span>
<span id="cb5-22"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@dataclass</span>(frozen<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># frozen=True makes it immutable + hashable</span></span>
<span id="cb5-23"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Point:</span>
<span id="cb5-24">    x: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span></span>
<span id="cb5-25">    y: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span></span>
<span id="cb5-26">    label: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span></span></code></pre></div></div>
</section>
<section id="advanced-dataclass-features" class="level3">
<h3 class="anchored" data-anchor-id="advanced-dataclass-features">Advanced Dataclass Features</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> dataclasses <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> dataclass, field, asdict, astuple</span>
<span id="cb6-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> typing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> ClassVar</span>
<span id="cb6-3"></span>
<span id="cb6-4"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@dataclass</span>(order<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>, slots<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># slots=True for memory efficiency (3.10+)</span></span>
<span id="cb6-5"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Employee:</span>
<span id="cb6-6">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ClassVar excluded from __init__ and __repr__</span></span>
<span id="cb6-7">    company: ClassVar[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Acme Corp"</span></span>
<span id="cb6-8"></span>
<span id="cb6-9">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Sort key (used for ordering)</span></span>
<span id="cb6-10">    sort_index: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> field(init<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">repr</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb6-11"></span>
<span id="cb6-12">    name: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span></span>
<span id="cb6-13">    salary: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span></span>
<span id="cb6-14">    skills: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> field(default_factory<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Mutable default!</span></span>
<span id="cb6-15"></span>
<span id="cb6-16">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> __post_init__(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb6-17">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.sort_index <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.salary  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Sort by salary</span></span>
<span id="cb6-18"></span>
<span id="cb6-19"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Usage</span></span>
<span id="cb6-20">emp <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Employee(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Alice"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">95000</span>, [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Python"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"SQL"</span>])</span>
<span id="cb6-21">emp_dict <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> asdict(emp)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Convert to dict</span></span>
<span id="cb6-22">emp_tuple <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> astuple(emp) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Convert to tuple</span></span></code></pre></div></div>
</section>
<section id="when-to-use-what" class="level3">
<h3 class="anchored" data-anchor-id="when-to-use-what">When to Use What</h3>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Use Case</th>
<th>Choice</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Simple data containers</td>
<td><code>@dataclass</code></td>
</tr>
<tr class="even">
<td>Immutable values (configs, coords)</td>
<td><code>@dataclass(frozen=True)</code></td>
</tr>
<tr class="odd">
<td>API validation + serialization</td>
<td><code>pydantic.BaseModel</code></td>
</tr>
<tr class="even">
<td>Named tuples (lightweight, immutable)</td>
<td><code>NamedTuple</code></td>
</tr>
<tr class="odd">
<td>Complex behavior + data</td>
<td>Regular class</td>
</tr>
<tr class="even">
<td>Minimal memory footprint</td>
<td><code>@dataclass(slots=True)</code> or <code>__slots__</code></td>
</tr>
</tbody>
</table>
<hr>
</section>
</section>
<section id="q4-what-are-metaclasses-and-when-would-you-use-them" class="level2">
<h2 class="anchored" data-anchor-id="q4-what-are-metaclasses-and-when-would-you-use-them">Q4: What are metaclasses and when would you use them?</h2>
<p><strong>Answer:</strong></p>
<p>A <strong>metaclass</strong> is the “class of a class” — it controls how classes themselves are created. Just as a class defines how instances behave, a metaclass defines how classes behave.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    META["Metaclass (type)&lt;br/&gt;Creates classes"]
    META --&gt; CLS["Class&lt;br/&gt;Created by metaclass"]
    CLS --&gt; OBJ["Instance&lt;br/&gt;Created by class"]

    META2["type('Dog', (Animal,), {'speak': ...})"]
    META2 --&gt; CLS2["class Dog(Animal):&lt;br/&gt;    def speak(): ..."]
    CLS2 --&gt; OBJ2["fido = Dog()"]

    style META fill:#ff7851,stroke:#333,color:#fff
    style CLS fill:#ffce67,stroke:#333
    style OBJ fill:#56cc9d,stroke:#333,color:#fff
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="how-class-creation-works" class="level3">
<h3 class="anchored" data-anchor-id="how-class-creation-works">How Class Creation Works</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># These are EQUIVALENT:</span></span>
<span id="cb7-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Dog:</span>
<span id="cb7-3">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> speak(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb7-4">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Woof"</span></span>
<span id="cb7-5"></span>
<span id="cb7-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># is the same as:</span></span>
<span id="cb7-7">Dog <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">type</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Dog"</span>, (), {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"speak"</span>: <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Woof"</span>})</span>
<span id="cb7-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># type(name, bases, namespace) → creates a new class</span></span></code></pre></div></div>
</section>
<section id="custom-metaclass-example-enforcing-rules" class="level3">
<h3 class="anchored" data-anchor-id="custom-metaclass-example-enforcing-rules">Custom Metaclass Example: Enforcing Rules</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> ValidatedMeta(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">type</span>):</span>
<span id="cb8-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Metaclass that enforces all methods have docstrings."""</span></span>
<span id="cb8-3"></span>
<span id="cb8-4">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__new__</span>(mcs, name, bases, namespace):</span>
<span id="cb8-5">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> key, value <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> namespace.items():</span>
<span id="cb8-6">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">callable</span>(value) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> key.startswith(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"_"</span>):</span>
<span id="cb8-7">                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> value.__doc__:</span>
<span id="cb8-8">                    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">TypeError</span>(</span>
<span id="cb8-9">                        <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Method '</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>key<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">' in class '</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>name<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">' must have a docstring"</span></span>
<span id="cb8-10">                    )</span>
<span id="cb8-11">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">super</span>().<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__new__</span>(mcs, name, bases, namespace)</span>
<span id="cb8-12"></span>
<span id="cb8-13"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> APIEndpoint(metaclass<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ValidatedMeta):</span>
<span id="cb8-14">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb8-15">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Handle GET request."""</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># OK: has docstring</span></span>
<span id="cb8-16">        ...</span>
<span id="cb8-17"></span>
<span id="cb8-18">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> post(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ERROR at class creation time!</span></span>
<span id="cb8-19">        ...          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># TypeError: Method 'post' must have a docstring</span></span></code></pre></div></div>
</section>
<section id="singleton-pattern-with-metaclass" class="level3">
<h3 class="anchored" data-anchor-id="singleton-pattern-with-metaclass">Singleton Pattern with Metaclass</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> SingletonMeta(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">type</span>):</span>
<span id="cb9-2">    _instances <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {}</span>
<span id="cb9-3"></span>
<span id="cb9-4">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__call__</span>(cls, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>args, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>kwargs):</span>
<span id="cb9-5">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> cls <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> cls._instances:</span>
<span id="cb9-6">            cls._instances[cls] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">super</span>().<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__call__</span>(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>args, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>kwargs)</span>
<span id="cb9-7">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> cls._instances[cls]</span>
<span id="cb9-8"></span>
<span id="cb9-9"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Database(metaclass<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>SingletonMeta):</span>
<span id="cb9-10">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb9-11">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.connection <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"connected"</span></span>
<span id="cb9-12"></span>
<span id="cb9-13">db1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Database()</span>
<span id="cb9-14">db2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Database()</span>
<span id="cb9-15"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> db1 <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> db2  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Same instance!</span></span></code></pre></div></div>
</section>
<section id="when-to-use-metaclasses-rarely" class="level3">
<h3 class="anchored" data-anchor-id="when-to-use-metaclasses-rarely">When to Use Metaclasses (Rarely!)</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 52%">
<col style="width: 47%">
</colgroup>
<thead>
<tr class="header">
<th>Use Case</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Framework/library design</td>
<td>Django models, SQLAlchemy declarative base</td>
</tr>
<tr class="even">
<td>Automatic registration</td>
<td>Plugin systems, API endpoint discovery</td>
</tr>
<tr class="odd">
<td>Enforcing interface contracts</td>
<td>Require methods/docstrings at class creation</td>
</tr>
<tr class="even">
<td>Singleton pattern</td>
<td>Database connections, config objects</td>
</tr>
</tbody>
</table>
</section>
<section id="alternatives-prefer-these-first" class="level3">
<h3 class="anchored" data-anchor-id="alternatives-prefer-these-first">Alternatives (Prefer These First)</h3>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Alternative</th>
<th>When</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>@dataclass</code> / decorators</td>
<td>Add behavior to classes</td>
</tr>
<tr class="even">
<td><code>__init_subclass__</code></td>
<td>Hook into subclass creation (simpler)</td>
</tr>
<tr class="odd">
<td>Abstract base classes (<code>ABC</code>)</td>
<td>Enforce interface contracts</td>
</tr>
<tr class="even">
<td>Class decorators</td>
<td>Modify class after creation</td>
</tr>
</tbody>
</table>
<blockquote class="blockquote">
<p><strong>Interview tip:</strong> “I rarely need metaclasses in application code, but I understand them because frameworks like Django/SQLAlchemy use them internally.”</p>
</blockquote>
<hr>
</section>
</section>
<section id="q5-how-does-pythons-exception-handling-work-and-what-are-best-practices" class="level2">
<h2 class="anchored" data-anchor-id="q5-how-does-pythons-exception-handling-work-and-what-are-best-practices">Q5: How does Python’s exception handling work, and what are best practices?</h2>
<p><strong>Answer:</strong></p>
<p>Python’s exception handling uses <code>try</code>/<code>except</code>/<code>else</code>/<code>finally</code> to manage errors gracefully. Understanding the full flow and best practices separates production code from beginner code.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    TRY["try:&lt;br/&gt;Code that might raise"]
    TRY --&gt;|"Exception raised"| EXCEPT["except SomeError as e:&lt;br/&gt;Handle error"]
    TRY --&gt;|"No exception"| ELSE["else:&lt;br/&gt;Code that runs only on success"]
    EXCEPT --&gt; FINALLY["finally:&lt;br/&gt;ALWAYS runs (cleanup)"]
    ELSE --&gt; FINALLY

    style TRY fill:#6cc3d5,stroke:#333,color:#fff
    style EXCEPT fill:#ff7851,stroke:#333,color:#fff
    style ELSE fill:#56cc9d,stroke:#333,color:#fff
    style FINALLY fill:#ffce67,stroke:#333
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="complete-exception-flow" class="level3">
<h3 class="anchored" data-anchor-id="complete-exception-flow">Complete Exception Flow</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> divide(a, b):</span>
<span id="cb10-2">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">try</span>:</span>
<span id="cb10-3">        result <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> a <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> b</span>
<span id="cb10-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">except</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">ZeroDivisionError</span>:</span>
<span id="cb10-5">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Cannot divide by zero"</span>)</span>
<span id="cb10-6">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span></span>
<span id="cb10-7">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">except</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">TypeError</span> <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> e:</span>
<span id="cb10-8">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Type error: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>e<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb10-9">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Re-raise the original exception</span></span>
<span id="cb10-10">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span>:</span>
<span id="cb10-11">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Only runs if NO exception occurred</span></span>
<span id="cb10-12">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Division successful: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>result<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb10-13">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> result</span>
<span id="cb10-14">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">finally</span>:</span>
<span id="cb10-15">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ALWAYS runs — even if return/raise happened above</span></span>
<span id="cb10-16">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Cleanup complete"</span>)</span></code></pre></div></div>
</section>
<section id="custom-exceptions-production-pattern" class="level3">
<h3 class="anchored" data-anchor-id="custom-exceptions-production-pattern">Custom Exceptions (Production Pattern)</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> AppError(<span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">Exception</span>):</span>
<span id="cb11-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Base exception for application."""</span></span>
<span id="cb11-3">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, message: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>, code: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>, details: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>):</span>
<span id="cb11-4">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">super</span>().<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(message)</span>
<span id="cb11-5">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.code <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> code</span>
<span id="cb11-6">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.details <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> details <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">or</span> {}</span>
<span id="cb11-7"></span>
<span id="cb11-8"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> ValidationError(AppError):</span>
<span id="cb11-9">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Raised when input validation fails."""</span></span>
<span id="cb11-10">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pass</span></span>
<span id="cb11-11"></span>
<span id="cb11-12"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> NotFoundError(AppError):</span>
<span id="cb11-13">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Raised when a resource is not found."""</span></span>
<span id="cb11-14">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">pass</span></span>
<span id="cb11-15"></span>
<span id="cb11-16"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Usage</span></span>
<span id="cb11-17"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_user(user_id: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>:</span>
<span id="cb11-18">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> user_id <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>:</span>
<span id="cb11-19">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> ValidationError(</span>
<span id="cb11-20">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"User ID must be positive"</span>,</span>
<span id="cb11-21">            code<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"INVALID_USER_ID"</span>,</span>
<span id="cb11-22">            details<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>{<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"user_id"</span>: user_id}</span>
<span id="cb11-23">        )</span>
<span id="cb11-24">    user <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> db.find(user_id)</span>
<span id="cb11-25">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> user:</span>
<span id="cb11-26">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> NotFoundError(</span>
<span id="cb11-27">            <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"User </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>user_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> not found"</span>,</span>
<span id="cb11-28">            code<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"USER_NOT_FOUND"</span></span>
<span id="cb11-29">        )</span>
<span id="cb11-30">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> user</span></code></pre></div></div>
</section>
<section id="best-practices" class="level3">
<h3 class="anchored" data-anchor-id="best-practices">Best Practices</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 66%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Practice</th>
<th>Why</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Catch specific exceptions, not bare <code>except:</code></td>
<td>Bare except catches <code>SystemExit</code>, <code>KeyboardInterrupt</code></td>
</tr>
<tr class="even">
<td>Use <code>else</code> for success-only code</td>
<td>Keeps try block minimal</td>
</tr>
<tr class="odd">
<td>Use <code>finally</code> for cleanup (or context managers)</td>
<td>Ensures resources are released</td>
</tr>
<tr class="even">
<td>Chain exceptions with <code>raise X from Y</code></td>
<td>Preserves original traceback</td>
</tr>
<tr class="odd">
<td>Don’t use exceptions for control flow</td>
<td>Performance penalty; use conditions instead</td>
</tr>
<tr class="even">
<td>Create exception hierarchies</td>
<td>Allows catching at different granularity levels</td>
</tr>
</tbody>
</table>
</section>
<section id="exception-chaining" class="level3">
<h3 class="anchored" data-anchor-id="exception-chaining">Exception Chaining</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">try</span>:</span>
<span id="cb12-2">    data <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> json.loads(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">raw_input</span>)</span>
<span id="cb12-3"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">except</span> json.JSONDecodeError <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> e:</span>
<span id="cb12-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> ValidationError(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Invalid JSON input"</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> e</span>
<span id="cb12-5">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Original exception preserved in __cause__</span></span>
<span id="cb12-6"></span>
<span id="cb12-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Python 3.11+: Exception Groups</span></span>
<span id="cb12-8"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> fetch_all(urls):</span>
<span id="cb12-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> asyncio.TaskGroup() <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> tg:</span>
<span id="cb12-10">        tasks <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [tg.create_task(fetch(url)) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> url <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> urls]</span>
<span id="cb12-11">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># If multiple tasks fail, raises ExceptionGroup</span></span></code></pre></div></div>
<hr>
</section>
</section>
<section id="q6-what-is-the-difference-between-classmethod-staticmethod-and-instance-methods" class="level2">
<h2 class="anchored" data-anchor-id="q6-what-is-the-difference-between-classmethod-staticmethod-and-instance-methods">Q6: What is the difference between <code>@classmethod</code>, <code>@staticmethod</code>, and instance methods?</h2>
<p><strong>Answer:</strong></p>
<p>Python classes have three types of methods, each receiving different first arguments and serving different purposes.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    subgraph Instance["Instance Method"]
        IM["def method(self, ...)"]
        IM --&gt; IMA["Access: instance + class data"]
        IM --&gt; IMB["Called on: object"]
    end

    subgraph Class["@classmethod"]
        CM["def method(cls, ...)"]
        CM --&gt; CMA["Access: class data only"]
        CM --&gt; CMB["Called on: class or object"]
    end

    subgraph Static["@staticmethod"]
        SM["def method(...)"]
        SM --&gt; SMA["Access: no class/instance data"]
        SM --&gt; SMB["Called on: class or object"]
    end

    style Instance fill:#56cc9d,stroke:#333,color:#fff
    style Class fill:#6cc3d5,stroke:#333,color:#fff
    style Static fill:#ffce67,stroke:#333
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="complete-example" class="level3">
<h3 class="anchored" data-anchor-id="complete-example">Complete Example</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Pizza:</span>
<span id="cb13-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Class variable</span></span>
<span id="cb13-3">    base_price <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">10.0</span></span>
<span id="cb13-4"></span>
<span id="cb13-5">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, toppings: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>], size: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"medium"</span>):</span>
<span id="cb13-6">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.toppings <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> toppings</span>
<span id="cb13-7">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.size <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> size</span>
<span id="cb13-8"></span>
<span id="cb13-9">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># INSTANCE METHOD: accesses self (instance data)</span></span>
<span id="cb13-10">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_price(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>:</span>
<span id="cb13-11">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Calculate price based on instance data."""</span></span>
<span id="cb13-12">        topping_cost <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.toppings) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.50</span></span>
<span id="cb13-13">        size_multiplier <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"small"</span>: <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"medium"</span>: <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"large"</span>: <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.3</span>}</span>
<span id="cb13-14">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> (<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.base_price <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> topping_cost) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> size_multiplier[<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.size]</span>
<span id="cb13-15"></span>
<span id="cb13-16">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># CLASS METHOD: accesses cls (class data), alternative constructor</span></span>
<span id="cb13-17">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@classmethod</span></span>
<span id="cb13-18">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> margherita(cls) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Pizza"</span>:</span>
<span id="cb13-19">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Factory method: create a standard Margherita."""</span></span>
<span id="cb13-20">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> cls([<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mozzarella"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tomato"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"basil"</span>])</span>
<span id="cb13-21"></span>
<span id="cb13-22">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@classmethod</span></span>
<span id="cb13-23">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> set_base_price(cls, price: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb13-24">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Modify class-level data."""</span></span>
<span id="cb13-25">        cls.base_price <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> price</span>
<span id="cb13-26"></span>
<span id="cb13-27">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># STATIC METHOD: no access to cls or self, utility function</span></span>
<span id="cb13-28">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@staticmethod</span></span>
<span id="cb13-29">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> validate_topping(topping: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bool</span>:</span>
<span id="cb13-30">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Pure utility — doesn't need class or instance data."""</span></span>
<span id="cb13-31">        valid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mozzarella"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pepperoni"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mushrooms"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"olives"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"basil"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tomato"</span>}</span>
<span id="cb13-32">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> topping.lower() <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> valid</span>
<span id="cb13-33"></span>
<span id="cb13-34"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Usage</span></span>
<span id="cb13-35">p <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Pizza.margherita()           <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># classmethod as factory</span></span>
<span id="cb13-36"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(p.get_price())             <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># instance method</span></span>
<span id="cb13-37">Pizza.validate_topping(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"olives"</span>) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># staticmethod — no instance needed</span></span></code></pre></div></div>
</section>
<section id="decision-guide" class="level3">
<h3 class="anchored" data-anchor-id="decision-guide">Decision Guide</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 66%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Question</th>
<th>Use</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Does it need <code>self</code> (instance data)?</td>
<td>Instance method</td>
</tr>
<tr class="even">
<td>Does it need <code>cls</code> (class data), or is it an alternative constructor?</td>
<td><code>@classmethod</code></td>
</tr>
<tr class="odd">
<td>Does it need neither — just a related utility?</td>
<td><code>@staticmethod</code></td>
</tr>
<tr class="even">
<td>Could it be a standalone function?</td>
<td>Consider module-level function instead</td>
</tr>
</tbody>
</table>
</section>
<section id="factory-pattern-with-classmethod" class="level3">
<h3 class="anchored" data-anchor-id="factory-pattern-with-classmethod">Factory Pattern with <code>@classmethod</code></h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb14-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Serializer:</span>
<span id="cb14-2">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, data: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>):</span>
<span id="cb14-3">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.data <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> data</span>
<span id="cb14-4"></span>
<span id="cb14-5">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@classmethod</span></span>
<span id="cb14-6">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> from_json(cls, json_string: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Serializer"</span>:</span>
<span id="cb14-7">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> cls(json.loads(json_string))</span>
<span id="cb14-8"></span>
<span id="cb14-9">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@classmethod</span></span>
<span id="cb14-10">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> from_csv(cls, csv_path: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Serializer"</span>:</span>
<span id="cb14-11">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">open</span>(csv_path) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> f:</span>
<span id="cb14-12">            reader <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> csv.DictReader(f)</span>
<span id="cb14-13">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> cls(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">next</span>(reader))</span>
<span id="cb14-14"></span>
<span id="cb14-15">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@classmethod</span></span>
<span id="cb14-16">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> from_yaml(cls, yaml_string: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Serializer"</span>:</span>
<span id="cb14-17">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> cls(yaml.safe_load(yaml_string))</span></code></pre></div></div>
<hr>
</section>
</section>
<section id="q7-what-are-__slots__-and-when-should-you-use-them" class="level2">
<h2 class="anchored" data-anchor-id="q7-what-are-__slots__-and-when-should-you-use-them">Q7: What are <code>__slots__</code> and when should you use them?</h2>
<p><strong>Answer:</strong></p>
<p><code>__slots__</code> replaces the default per-instance <code>__dict__</code> with a fixed set of attribute slots, providing <strong>significant memory savings</strong> and <strong>slightly faster attribute access</strong>.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph LR
    subgraph WithDict["Normal Class (with __dict__)"]
        D1["Each instance has a dict"]
        D2["~200+ bytes overhead per instance"]
        D3["Dynamic: can add any attribute"]
    end

    subgraph WithSlots["Class with __slots__"]
        S1["Fixed attribute slots"]
        S2["~40-80% less memory"]
        S3["Static: only declared attributes"]
    end

    style WithDict fill:#ff7851,stroke:#333,color:#fff
    style WithSlots fill:#56cc9d,stroke:#333,color:#fff
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="basic-usage" class="level3">
<h3 class="anchored" data-anchor-id="basic-usage">Basic Usage</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb15-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> PointRegular:</span>
<span id="cb15-2">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, x, y):</span>
<span id="cb15-3">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> x</span>
<span id="cb15-4">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y</span>
<span id="cb15-5"></span>
<span id="cb15-6"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> PointSlots:</span>
<span id="cb15-7">    <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">__slots__</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y"</span>)</span>
<span id="cb15-8"></span>
<span id="cb15-9">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, x, y):</span>
<span id="cb15-10">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.x <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> x</span>
<span id="cb15-11">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> y</span>
<span id="cb15-12"></span>
<span id="cb15-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Memory comparison (1 million instances)</span></span>
<span id="cb15-14"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> sys</span>
<span id="cb15-15"></span>
<span id="cb15-16">regular <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> PointRegular(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.0</span>)</span>
<span id="cb15-17">slotted <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> PointSlots(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.0</span>)</span>
<span id="cb15-18"></span>
<span id="cb15-19"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(sys.getsizeof(regular.__dict__))  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 104 bytes (just the dict!)</span></span>
<span id="cb15-20"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># PointSlots has no __dict__ — memory is inline</span></span>
<span id="cb15-21"></span>
<span id="cb15-22"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Dynamic attribute behavior</span></span>
<span id="cb15-23">regular.z <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.0</span>       <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Works — __dict__ allows anything</span></span>
<span id="cb15-24"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># slotted.z = 3.0    # AttributeError! Not in __slots__</span></span></code></pre></div></div>
</section>
<section id="memory-savings-at-scale" class="level3">
<h3 class="anchored" data-anchor-id="memory-savings-at-scale">Memory Savings at Scale</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb16-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># For 1 million instances:</span></span>
<span id="cb16-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Regular class: ~170 bytes/instance × 1M = ~170 MB</span></span>
<span id="cb16-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Slotted class: ~56 bytes/instance × 1M = ~56 MB</span></span>
<span id="cb16-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Savings: ~67%!</span></span>
<span id="cb16-5"></span>
<span id="cb16-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Python 3.10+ dataclass with slots</span></span>
<span id="cb16-7"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> dataclasses <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> dataclass</span>
<span id="cb16-8"></span>
<span id="cb16-9"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@dataclass</span>(slots<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb16-10"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Coordinate:</span>
<span id="cb16-11">    x: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span></span>
<span id="cb16-12">    y: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span></span>
<span id="cb16-13">    z: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.0</span></span></code></pre></div></div>
</section>
<section id="trade-offs" class="level3">
<h3 class="anchored" data-anchor-id="trade-offs">Trade-offs</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 16%">
<col style="width: 27%">
<col style="width: 56%">
</colgroup>
<thead>
<tr class="header">
<th>Aspect</th>
<th><code>__slots__</code></th>
<th>Regular (with <code>__dict__</code>)</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Memory per instance</td>
<td>Much lower</td>
<td>Higher (dict overhead)</td>
</tr>
<tr class="even">
<td>Attribute access speed</td>
<td>Slightly faster</td>
<td>Slightly slower</td>
</tr>
<tr class="odd">
<td>Dynamic attributes</td>
<td>Not allowed</td>
<td>Allowed</td>
</tr>
<tr class="even">
<td><code>__dict__</code> available</td>
<td>No (unless explicitly added)</td>
<td>Yes</td>
</tr>
<tr class="odd">
<td>Inheritance</td>
<td>Must redeclare slots in subclass</td>
<td>Works naturally</td>
</tr>
<tr class="even">
<td>Pickling/serialization</td>
<td>May need custom <code>__getstate__</code></td>
<td>Works automatically</td>
</tr>
<tr class="odd">
<td>Weak references</td>
<td>Need <code>__weakref__</code> in slots</td>
<td>Works automatically</td>
</tr>
</tbody>
</table>
</section>
<section id="when-to-use-__slots__" class="level3">
<h3 class="anchored" data-anchor-id="when-to-use-__slots__">When to Use <code>__slots__</code></h3>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Use</th>
<th>Don’t Use</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Millions of instances (data processing)</td>
<td>Few instances</td>
</tr>
<tr class="even">
<td>Performance-critical inner loops</td>
<td>Prototyping/exploration</td>
</tr>
<tr class="odd">
<td>Known, fixed set of attributes</td>
<td>Need dynamic attributes</td>
</tr>
<tr class="even">
<td>ORM model objects</td>
<td>Classes using multiple inheritance heavily</td>
</tr>
</tbody>
</table>
<hr>
</section>
</section>
<section id="q8-how-do-you-write-effective-tests-in-python-with-pytest" class="level2">
<h2 class="anchored" data-anchor-id="q8-how-do-you-write-effective-tests-in-python-with-pytest">Q8: How do you write effective tests in Python with <code>pytest</code>?</h2>
<p><strong>Answer:</strong></p>
<p><code>pytest</code> is Python’s most popular testing framework — simpler than <code>unittest</code>, with powerful fixtures, parametrization, and plugin ecosystem.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    TEST["Testing Pyramid"]
    TEST --&gt; UNIT["Unit Tests (70%)&lt;br/&gt;Fast, isolated, many"]
    TEST --&gt; INT["Integration Tests (20%)&lt;br/&gt;Components together"]
    TEST --&gt; E2E["E2E Tests (10%)&lt;br/&gt;Full system, slow"]

    subgraph Pytest["pytest Features"]
        F1["Simple assertions (assert x == y)"]
        F2["Fixtures (setup/teardown)"]
        F3["Parametrize (multiple inputs)"]
        F4["Mocking (unittest.mock)"]
        F5["Markers (skip, xfail, slow)"]
    end

    style TEST fill:#56cc9d,stroke:#333,color:#fff
    style UNIT fill:#6cc3d5,stroke:#333,color:#fff
    style Pytest fill:#ffce67,stroke:#333
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="basic-test-structure" class="level3">
<h3 class="anchored" data-anchor-id="basic-test-structure">Basic Test Structure</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb17-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># test_calculator.py</span></span>
<span id="cb17-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pytest</span>
<span id="cb17-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> calculator <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Calculator</span>
<span id="cb17-4"></span>
<span id="cb17-5"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> TestCalculator:</span>
<span id="cb17-6">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Group related tests in a class."""</span></span>
<span id="cb17-7"></span>
<span id="cb17-8">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> test_add_positive_numbers(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb17-9">        calc <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Calculator()</span>
<span id="cb17-10">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> calc.add(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span></span>
<span id="cb17-11"></span>
<span id="cb17-12">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> test_add_negative_numbers(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb17-13">        calc <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Calculator()</span>
<span id="cb17-14">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> calc.add(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb17-15"></span>
<span id="cb17-16">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> test_divide_by_zero_raises(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb17-17">        calc <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Calculator()</span>
<span id="cb17-18">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> pytest.raises(<span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">ZeroDivisionError</span>):</span>
<span id="cb17-19">            calc.divide(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span></code></pre></div></div>
</section>
<section id="fixtures-shared-setupteardown" class="level3">
<h3 class="anchored" data-anchor-id="fixtures-shared-setupteardown">Fixtures: Shared Setup/Teardown</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb18-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pytest</span>
<span id="cb18-2"></span>
<span id="cb18-3"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@pytest.fixture</span></span>
<span id="cb18-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> db_connection():</span>
<span id="cb18-5">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Setup: create connection. Teardown: close it."""</span></span>
<span id="cb18-6">    conn <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Database.<span class="ex" style="color: null;
background-color: null;
font-style: inherit;">connect</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"test_db"</span>)</span>
<span id="cb18-7">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">yield</span> conn  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Test runs here</span></span>
<span id="cb18-8">    conn.close()  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Cleanup after test</span></span>
<span id="cb18-9"></span>
<span id="cb18-10"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@pytest.fixture</span></span>
<span id="cb18-11"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> sample_user(db_connection):</span>
<span id="cb18-12">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Fixtures can depend on other fixtures."""</span></span>
<span id="cb18-13">    user <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> db_connection.create_user(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Alice"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"alice@test.com"</span>)</span>
<span id="cb18-14">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">yield</span> user</span>
<span id="cb18-15">    db_connection.delete_user(user.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">id</span>)</span>
<span id="cb18-16"></span>
<span id="cb18-17"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> test_user_email(sample_user):</span>
<span id="cb18-18">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> sample_user.email <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"alice@test.com"</span></span></code></pre></div></div>
</section>
<section id="parametrize-test-multiple-inputs" class="level3">
<h3 class="anchored" data-anchor-id="parametrize-test-multiple-inputs">Parametrize: Test Multiple Inputs</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb19-1"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@pytest.mark.parametrize</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"input_val,expected"</span>, [</span>
<span id="cb19-2">    (<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"hello"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"HELLO"</span>),</span>
<span id="cb19-3">    (<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"world"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"WORLD"</span>),</span>
<span id="cb19-4">    (<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Python"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"PYTHON"</span>),</span>
<span id="cb19-5">    (<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>),</span>
<span id="cb19-6">])</span>
<span id="cb19-7"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> test_uppercase(input_val, expected):</span>
<span id="cb19-8">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> input_val.upper() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> expected</span>
<span id="cb19-9"></span>
<span id="cb19-10"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@pytest.mark.parametrize</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"a,b,expected"</span>, [</span>
<span id="cb19-11">    (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>),</span>
<span id="cb19-12">    (<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>),</span>
<span id="cb19-13">    (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>),</span>
<span id="cb19-14">    (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>),</span>
<span id="cb19-15">])</span>
<span id="cb19-16"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> test_add(a, b, expected):</span>
<span id="cb19-17">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> add(a, b) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> expected</span></code></pre></div></div>
</section>
<section id="mocking-external-dependencies" class="level3">
<h3 class="anchored" data-anchor-id="mocking-external-dependencies">Mocking External Dependencies</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb20" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb20-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> unittest.mock <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> patch, MagicMock</span>
<span id="cb20-2"></span>
<span id="cb20-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> test_api_call():</span>
<span id="cb20-4">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Mock external HTTP calls."""</span></span>
<span id="cb20-5">    mock_response <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> MagicMock()</span>
<span id="cb20-6">    mock_response.status_code <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span></span>
<span id="cb20-7">    mock_response.json.return_value <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"name"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Alice"</span>}</span>
<span id="cb20-8"></span>
<span id="cb20-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> patch(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"requests.get"</span>, return_value<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>mock_response):</span>
<span id="cb20-10">        result <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> get_user_from_api(user_id<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb20-11">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> result[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"name"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Alice"</span></span>
<span id="cb20-12"></span>
<span id="cb20-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Or as a decorator</span></span>
<span id="cb20-14"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@patch</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"myapp.services.send_email"</span>)</span>
<span id="cb20-15"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> test_registration(mock_send_email):</span>
<span id="cb20-16">    register_user(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"alice@test.com"</span>)</span>
<span id="cb20-17">    mock_send_email.assert_called_once_with(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"alice@test.com"</span>, subject<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Welcome!"</span>)</span></code></pre></div></div>
</section>
<section id="testing-best-practices" class="level3">
<h3 class="anchored" data-anchor-id="testing-best-practices">Testing Best Practices</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 55%">
<col style="width: 44%">
</colgroup>
<thead>
<tr class="header">
<th>Practice</th>
<th>Reason</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Test one behavior per test</td>
<td>Clear failure messages</td>
</tr>
<tr class="even">
<td>Use descriptive test names</td>
<td><code>test_user_login_fails_with_wrong_password</code></td>
</tr>
<tr class="odd">
<td>Arrange-Act-Assert (AAA) pattern</td>
<td>Consistent structure</td>
</tr>
<tr class="even">
<td>Don’t test implementation details</td>
<td>Tests shouldn’t break on refactoring</td>
</tr>
<tr class="odd">
<td>Use <code>conftest.py</code> for shared fixtures</td>
<td>DRY across test files</td>
</tr>
<tr class="even">
<td>Mark slow tests with <code>@pytest.mark.slow</code></td>
<td>Run fast tests separately</td>
</tr>
</tbody>
</table>
<hr>
</section>
</section>
<section id="q9-what-is-the-collections-module-and-its-key-data-structures" class="level2">
<h2 class="anchored" data-anchor-id="q9-what-is-the-collections-module-and-its-key-data-structures">Q9: What is the <code>collections</code> module and its key data structures?</h2>
<p><strong>Answer:</strong></p>
<p>The <code>collections</code> module provides <strong>specialized container types</strong> that extend Python’s built-in <code>dict</code>, <code>list</code>, <code>set</code>, and <code>tuple</code> with additional functionality for common patterns.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    COLL["collections module"]
    COLL --&gt; DD["defaultdict&lt;br/&gt;Auto-initializing dict"]
    COLL --&gt; CT["Counter&lt;br/&gt;Element counting"]
    COLL --&gt; DQ["deque&lt;br/&gt;Double-ended queue"]
    COLL --&gt; OD["OrderedDict&lt;br/&gt;Ordered key operations"]
    COLL --&gt; NT["namedtuple&lt;br/&gt;Lightweight immutable record"]
    COLL --&gt; CM["ChainMap&lt;br/&gt;Multiple dict lookup"]

    style COLL fill:#56cc9d,stroke:#333,color:#fff
    style DD fill:#6cc3d5,stroke:#333,color:#fff
    style CT fill:#ffce67,stroke:#333
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="defaultdict-eliminates-key-existence-checks" class="level3">
<h3 class="anchored" data-anchor-id="defaultdict-eliminates-key-existence-checks"><code>defaultdict</code> — Eliminates Key-Existence Checks</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb21-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> collections <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> defaultdict</span>
<span id="cb21-2"></span>
<span id="cb21-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># WITHOUT defaultdict</span></span>
<span id="cb21-4">word_groups <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {}</span>
<span id="cb21-5"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> word <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> words:</span>
<span id="cb21-6">    first_letter <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> word[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb21-7">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> first_letter <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> word_groups:</span>
<span id="cb21-8">        word_groups[first_letter] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> []</span>
<span id="cb21-9">    word_groups[first_letter].append(word)</span>
<span id="cb21-10"></span>
<span id="cb21-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># WITH defaultdict — cleaner!</span></span>
<span id="cb21-12">word_groups <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> defaultdict(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>)</span>
<span id="cb21-13"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> word <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> words:</span>
<span id="cb21-14">    word_groups[word[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]].append(word)</span>
<span id="cb21-15"></span>
<span id="cb21-16"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Common factory functions</span></span>
<span id="cb21-17">counts <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> defaultdict(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>)      <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Missing keys default to 0</span></span>
<span id="cb21-18">groups <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> defaultdict(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>)     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Missing keys default to []</span></span>
<span id="cb21-19">nested <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> defaultdict(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>)     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Missing keys default to {}</span></span>
<span id="cb21-20">sets <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> defaultdict(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">set</span>)        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Missing keys default to set()</span></span></code></pre></div></div>
</section>
<section id="counter-counting-made-easy" class="level3">
<h3 class="anchored" data-anchor-id="counter-counting-made-easy"><code>Counter</code> — Counting Made Easy</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb22" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb22-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> collections <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Counter</span>
<span id="cb22-2"></span>
<span id="cb22-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Count elements</span></span>
<span id="cb22-4">words <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"apple"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"banana"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"apple"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cherry"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"banana"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"apple"</span>]</span>
<span id="cb22-5">word_counts <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Counter(words)</span>
<span id="cb22-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Counter({'apple': 3, 'banana': 2, 'cherry': 1})</span></span>
<span id="cb22-7"></span>
<span id="cb22-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Most common</span></span>
<span id="cb22-9">word_counts.most_common(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># [('apple', 3), ('banana', 2)]</span></span>
<span id="cb22-10"></span>
<span id="cb22-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Arithmetic</span></span>
<span id="cb22-12">c1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Counter(a<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, b<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb22-13">c2 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Counter(a<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, b<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb22-14">c1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> c2   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Counter({'a': 4, 'b': 3})</span></span>
<span id="cb22-15">c1 <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> c2   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Counter({'a': 2})  — drops zero/negative</span></span>
<span id="cb22-16"></span>
<span id="cb22-17"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Count characters in string</span></span>
<span id="cb22-18">Counter(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mississippi"</span>)</span>
<span id="cb22-19"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Counter({'s': 4, 'i': 4, 'p': 2, 'm': 1})</span></span></code></pre></div></div>
</section>
<section id="deque-fast-appendspops-from-both-ends" class="level3">
<h3 class="anchored" data-anchor-id="deque-fast-appendspops-from-both-ends"><code>deque</code> — Fast Appends/Pops from Both Ends</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb23" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb23-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> collections <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> deque</span>
<span id="cb23-2"></span>
<span id="cb23-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># O(1) operations on both ends (list.pop(0) is O(n)!)</span></span>
<span id="cb23-4">dq <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> deque([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>])</span>
<span id="cb23-5">dq.appendleft(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># [0, 1, 2, 3]</span></span>
<span id="cb23-6">dq.popleft()       <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 0, deque is [1, 2, 3]</span></span>
<span id="cb23-7"></span>
<span id="cb23-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Fixed-size sliding window</span></span>
<span id="cb23-9">recent_logs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> deque(maxlen<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>)</span>
<span id="cb23-10">recent_logs.append(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"event1"</span>)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Auto-removes oldest when full</span></span>
<span id="cb23-11"></span>
<span id="cb23-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># BFS implementation</span></span>
<span id="cb23-13"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> bfs(graph, start):</span>
<span id="cb23-14">    visited <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">set</span>()</span>
<span id="cb23-15">    queue <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> deque([start])</span>
<span id="cb23-16">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">while</span> queue:</span>
<span id="cb23-17">        node <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> queue.popleft()  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># O(1) vs list.pop(0) O(n)</span></span>
<span id="cb23-18">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> node <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> visited:</span>
<span id="cb23-19">            visited.add(node)</span>
<span id="cb23-20">            queue.extend(graph[node])</span>
<span id="cb23-21">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> visited</span></code></pre></div></div>
</section>
<section id="namedtuple-lightweight-immutable-records" class="level3">
<h3 class="anchored" data-anchor-id="namedtuple-lightweight-immutable-records"><code>namedtuple</code> — Lightweight Immutable Records</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb24" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb24-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> collections <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> namedtuple</span>
<span id="cb24-2"></span>
<span id="cb24-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Create a type</span></span>
<span id="cb24-4">Point <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> namedtuple(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Point"</span>, [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y"</span>])</span>
<span id="cb24-5">Color <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> namedtuple(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Color"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"red green blue"</span>)</span>
<span id="cb24-6"></span>
<span id="cb24-7">p <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Point(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span>
<span id="cb24-8"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(p.x, p.y)    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Named access</span></span>
<span id="cb24-9"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(p[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], p[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Index access</span></span>
<span id="cb24-10">x, y <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> p           <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Unpacking</span></span>
<span id="cb24-11"></span>
<span id="cb24-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># With defaults (Python 3.6.1+)</span></span>
<span id="cb24-13">Server <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> namedtuple(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Server"</span>, [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"host"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"port"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"protocol"</span>], defaults<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"https"</span>])</span>
<span id="cb24-14">s <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Server(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"example.com"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">443</span>)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># protocol defaults to "https"</span></span></code></pre></div></div>
</section>
<section id="performance-comparison" class="level3">
<h3 class="anchored" data-anchor-id="performance-comparison">Performance Comparison</h3>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Operation</th>
<th><code>list</code></th>
<th><code>deque</code></th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Append right</td>
<td>O(1) amortized</td>
<td>O(1)</td>
</tr>
<tr class="even">
<td>Pop right</td>
<td>O(1)</td>
<td>O(1)</td>
</tr>
<tr class="odd">
<td>Append left</td>
<td>O(n)</td>
<td>O(1)</td>
</tr>
<tr class="even">
<td>Pop left</td>
<td>O(n)</td>
<td>O(1)</td>
</tr>
<tr class="odd">
<td>Random access <code>[i]</code></td>
<td>O(1)</td>
<td>O(n)</td>
</tr>
</tbody>
</table>
<hr>
</section>
</section>
<section id="q10-what-are-python-descriptors-and-the-descriptor-protocol" class="level2">
<h2 class="anchored" data-anchor-id="q10-what-are-python-descriptors-and-the-descriptor-protocol">Q10: What are Python descriptors and the descriptor protocol?</h2>
<p><strong>Answer:</strong></p>
<p>A <strong>descriptor</strong> is any object that defines <code>__get__</code>, <code>__set__</code>, or <code>__delete__</code> methods. Descriptors power Python’s property system, classmethods, staticmethods, and <code>__slots__</code>.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    DESC["Descriptor Protocol"]
    DESC --&gt; GET["__get__(self, obj, objtype)&lt;br/&gt;Attribute access: obj.attr"]
    DESC --&gt; SET["__set__(self, obj, value)&lt;br/&gt;Assignment: obj.attr = value"]
    DESC --&gt; DEL["__delete__(self, obj)&lt;br/&gt;Deletion: del obj.attr"]

    subgraph Types["Descriptor Types"]
        DD["Data Descriptor&lt;br/&gt;Defines __set__ and/or __delete__&lt;br/&gt;Takes priority over instance __dict__"]
        ND["Non-Data Descriptor&lt;br/&gt;Only defines __get__&lt;br/&gt;Instance __dict__ takes priority"]
    end

    style DESC fill:#56cc9d,stroke:#333,color:#fff
    style Types fill:#6cc3d5,stroke:#333,color:#fff
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="how-property-works-under-the-hood" class="level3">
<h3 class="anchored" data-anchor-id="how-property-works-under-the-hood">How <code>property</code> Works Under the Hood</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb25" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb25-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># property() is actually a descriptor!</span></span>
<span id="cb25-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">property</span>:</span>
<span id="cb25-3">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, fget<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>, fset<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>, fdel<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>):</span>
<span id="cb25-4">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.fget <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fget</span>
<span id="cb25-5">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.fset <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fset</span>
<span id="cb25-6">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.fdel <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fdel</span>
<span id="cb25-7"></span>
<span id="cb25-8">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__get__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, obj, objtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>):</span>
<span id="cb25-9">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> obj <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb25-10">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span></span>
<span id="cb25-11">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.fget(obj)</span>
<span id="cb25-12"></span>
<span id="cb25-13">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__set__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, obj, value):</span>
<span id="cb25-14">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.fset(obj, value)</span>
<span id="cb25-15"></span>
<span id="cb25-16">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__delete__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, obj):</span>
<span id="cb25-17">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.fdel(obj)</span></code></pre></div></div>
</section>
<section id="custom-descriptor-validated-attribute" class="level3">
<h3 class="anchored" data-anchor-id="custom-descriptor-validated-attribute">Custom Descriptor: Validated Attribute</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb26" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb26-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Validated:</span>
<span id="cb26-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Descriptor that validates values on assignment."""</span></span>
<span id="cb26-3"></span>
<span id="cb26-4">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, min_value<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>, max_value<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>):</span>
<span id="cb26-5">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.min_value <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> min_value</span>
<span id="cb26-6">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_value <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> max_value</span>
<span id="cb26-7"></span>
<span id="cb26-8">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__set_name__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, owner, name):</span>
<span id="cb26-9">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Called automatically when descriptor is assigned to a class attribute."""</span></span>
<span id="cb26-10">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> name</span>
<span id="cb26-11">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.private_name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"_</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>name<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span></span>
<span id="cb26-12"></span>
<span id="cb26-13">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__get__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, obj, objtype<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>):</span>
<span id="cb26-14">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> obj <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb26-15">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span></span>
<span id="cb26-16">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">getattr</span>(obj, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.private_name, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>)</span>
<span id="cb26-17"></span>
<span id="cb26-18">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__set__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, obj, value):</span>
<span id="cb26-19">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.min_value <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> value <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.min_value:</span>
<span id="cb26-20">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">ValueError</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>name<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> must be &gt;= </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>min_value<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">, got </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>value<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb26-21">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_value <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> value <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.max_value:</span>
<span id="cb26-22">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">ValueError</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>name<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> must be &lt;= </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>max_value<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">, got </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>value<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb26-23">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">setattr</span>(obj, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.private_name, value)</span>
<span id="cb26-24"></span>
<span id="cb26-25"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Usage — validation happens automatically on assignment</span></span>
<span id="cb26-26"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Product:</span>
<span id="cb26-27">    price <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Validated(min_value<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb26-28">    quantity <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Validated(min_value<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, max_value<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10000</span>)</span>
<span id="cb26-29">    rating <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Validated(min_value<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, max_value<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)</span>
<span id="cb26-30"></span>
<span id="cb26-31">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, name, price, quantity):</span>
<span id="cb26-32">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.name <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> name</span>
<span id="cb26-33">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.price <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> price        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Triggers Validated.__set__</span></span>
<span id="cb26-34">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.quantity <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> quantity   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Triggers Validated.__set__</span></span>
<span id="cb26-35"></span>
<span id="cb26-36">p <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Product(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Widget"</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">9.99</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>)</span>
<span id="cb26-37"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># p.price = -5  # ValueError: price must be &gt;= 0, got -5</span></span></code></pre></div></div>
</section>
<section id="attribute-lookup-order" class="level3">
<h3 class="anchored" data-anchor-id="attribute-lookup-order">Attribute Lookup Order</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 37%">
<col style="width: 29%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Priority</th>
<th>Source</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>1 (highest)</td>
<td>Data descriptor on class</td>
<td><code>property</code>, <code>Validated</code> above</td>
</tr>
<tr class="even">
<td>2</td>
<td>Instance <code>__dict__</code></td>
<td><code>self.x = 5</code></td>
</tr>
<tr class="odd">
<td>3</td>
<td>Non-data descriptor on class</td>
<td>Functions (become bound methods)</td>
</tr>
<tr class="even">
<td>4</td>
<td>Class <code>__dict__</code></td>
<td>Class variables</td>
</tr>
<tr class="odd">
<td>5 (lowest)</td>
<td><code>__getattr__</code></td>
<td>Fallback hook</td>
</tr>
</tbody>
</table>
</section>
<section id="built-in-descriptors-you-already-use" class="level3">
<h3 class="anchored" data-anchor-id="built-in-descriptors-you-already-use">Built-in Descriptors You Already Use</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb27" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb27-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># These are ALL descriptors:</span></span>
<span id="cb27-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> MyClass:</span>
<span id="cb27-3">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@property</span>          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Data descriptor</span></span>
<span id="cb27-4">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> value(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>): ...</span>
<span id="cb27-5"></span>
<span id="cb27-6">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@classmethod</span>       <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Non-data descriptor</span></span>
<span id="cb27-7">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> create(cls): ...</span>
<span id="cb27-8"></span>
<span id="cb27-9">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@staticmethod</span>      <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Non-data descriptor</span></span>
<span id="cb27-10">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> utility(): ...</span>
<span id="cb27-11"></span>
<span id="cb27-12">    <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">__slots__</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x"</span>,) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Creates data descriptors for each slot</span></span></code></pre></div></div>
<hr>
</section>
</section>
<section id="summary-table" class="level2">
<h2 class="anchored" data-anchor-id="summary-table">Summary Table</h2>
<table class="caption-top table">
<colgroup>
<col style="width: 13%">
<col style="width: 30%">
<col style="width: 56%">
</colgroup>
<thead>
<tr class="header">
<th>#</th>
<th>Topic</th>
<th>Key Concept</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>1</td>
<td>async/await</td>
<td>Cooperative concurrency via event loop; use for I/O-bound tasks</td>
</tr>
<tr class="even">
<td>2</td>
<td>Type Hints</td>
<td>Static annotations for tools (mypy/pyright); <code>Protocol</code> for structural typing</td>
</tr>
<tr class="odd">
<td>3</td>
<td>Dataclasses</td>
<td>Auto-generate <code>__init__</code>, <code>__repr__</code>, <code>__eq__</code>; use <code>frozen=True</code> for immutability</td>
</tr>
<tr class="even">
<td>4</td>
<td>Metaclasses</td>
<td>“Classes of classes”; control class creation; prefer <code>__init_subclass__</code> alternatives</td>
</tr>
<tr class="odd">
<td>5</td>
<td>Exception Handling</td>
<td>Specific catches, <code>else</code>/<code>finally</code>, custom hierarchies, exception chaining</td>
</tr>
<tr class="even">
<td>6</td>
<td>classmethod/staticmethod</td>
<td><code>cls</code> for factories/class data, <code>self</code> for instance, static for utilities</td>
</tr>
<tr class="odd">
<td>7</td>
<td><code>__slots__</code></td>
<td>Replace <code>__dict__</code> with fixed slots; 40-80% memory savings at scale</td>
</tr>
<tr class="even">
<td>8</td>
<td>Testing (pytest)</td>
<td>Fixtures, parametrize, mocking; test behavior not implementation</td>
</tr>
<tr class="odd">
<td>9</td>
<td>collections</td>
<td><code>defaultdict</code>, <code>Counter</code>, <code>deque</code>, <code>namedtuple</code> for specialized containers</td>
</tr>
<tr class="even">
<td>10</td>
<td>Descriptors</td>
<td><code>__get__</code>/<code>__set__</code>/<code>__delete__</code> protocol; powers <code>property</code>, <code>@classmethod</code></td>
</tr>
</tbody>
</table>
<hr>
</section>
<section id="whats-next" class="level2">
<h2 class="anchored" data-anchor-id="whats-next">What’s Next?</h2>
<p>This article covered advanced Python internals and production patterns. For related content:</p>
<ul>
<li><strong>Python fundamentals:</strong> <a href="../../posts/python-swe-interview/Python-SWE-Interview-QA-1.html">Python SWE Interview QA - 1</a></li>
<li><strong>Machine learning concepts:</strong> <a href="../../posts/ml-interview/ML-Interview-QA-1.html">ML Interview QA - 1</a> and <a href="../../posts/ml-interview/ML-Interview-QA-2.html">ML Interview QA - 2</a></li>
<li><strong>LLM architecture and concepts:</strong> <a href="../../posts/llm-interview/LLM-Interview-QA-1.html">LLM Interview QA - 1</a></li>
<li><strong>Advanced LLM topics:</strong> <a href="../../posts/llm-interview/LLM-Interview-QA-2.html">LLM Interview QA - 2</a></li>
<li><strong>LLM configuration and decoding:</strong> <a href="../../posts/llm-interview/LLM-Interview-QA-3.html">LLM Interview QA - 3</a></li>
</ul>


</section>

 ]]></description>
  <guid>https://vectoringai.com/posts/swe-interview/Python-SWE-Interview-QA-2.html</guid>
  <pubDate>Wed, 20 May 2026 00:00:00 GMT</pubDate>
  <media:content url="https://vectoringai.com/images/python-swe-interview/thumb_python_swe_interview_qa_300.png" medium="image" type="image/png" height="96" width="144"/>
</item>
<item>
  <title>Python SWE Interview QA - 3</title>
  <dc:creator>Vectoring AI</dc:creator>
  <link>https://vectoringai.com/posts/swe-interview/Python-SWE-Interview-QA-3.html</link>
  <description><![CDATA[ 




<section id="introduction" class="level2">
<h2 class="anchored" data-anchor-id="introduction">Introduction</h2>
<p>This is <strong>Part 3</strong> of our Python SWE Interview QA series, focused on <strong>best practices, design patterns, and source code structure</strong> — the topics that distinguish engineers who write production-quality code from those who just make things work.</p>
<blockquote class="blockquote">
<p>For foundational Python topics, see <a href="../../posts/python-swe-interview/Python-SWE-Interview-QA-1.html">Python SWE Interview QA - 1</a>. For advanced internals (async, metaclasses, descriptors), see <a href="../../posts/python-swe-interview/Python-SWE-Interview-QA-2.html">Python SWE Interview QA - 2</a>.</p>
</blockquote>
<hr>
</section>
<section id="q1-how-should-a-production-python-project-be-structured" class="level2">
<h2 class="anchored" data-anchor-id="q1-how-should-a-production-python-project-be-structured">Q1: How should a production Python project be structured?</h2>
<p><strong>Answer:</strong></p>
<p>A well-structured project separates concerns, makes navigation intuitive, and supports testing, packaging, and deployment without friction.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    ROOT["project-root/"]
    ROOT --&gt; SRC["src/mypackage/&lt;br/&gt;Application code"]
    ROOT --&gt; TESTS["tests/&lt;br/&gt;Test mirror of src"]
    ROOT --&gt; CONF["Config files&lt;br/&gt;pyproject.toml, Makefile"]
    ROOT --&gt; DOCS["docs/&lt;br/&gt;Documentation"]
    ROOT --&gt; SCRIPTS["scripts/&lt;br/&gt;One-off utilities"]

    SRC --&gt; CORE["core/&lt;br/&gt;Business logic"]
    SRC --&gt; API["api/&lt;br/&gt;HTTP/CLI interface"]
    SRC --&gt; INFRA["infra/&lt;br/&gt;DB, cache, external services"]
    SRC --&gt; MODELS["models/&lt;br/&gt;Data structures"]

    style ROOT fill:#56cc9d,stroke:#333,color:#fff
    style SRC fill:#6cc3d5,stroke:#333,color:#fff
    style TESTS fill:#ffce67,stroke:#333
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="recommended-layout-src-layout" class="level3">
<h3 class="anchored" data-anchor-id="recommended-layout-src-layout">Recommended Layout (src-layout)</h3>
<pre><code>my-project/
├── pyproject.toml          # Build config, dependencies, tool settings
├── README.md
├── Makefile                # Common commands (test, lint, format)
├── .env.example            # Environment variable template
├── src/
│   └── mypackage/
│       ├── __init__.py     # Package marker + public API exports
│       ├── main.py         # Entry point (CLI or app startup)
│       ├── config.py       # Settings (from env vars / config files)
│       ├── models/         # Data models (dataclasses, Pydantic)
│       │   ├── __init__.py
│       │   ├── user.py
│       │   └── order.py
│       ├── services/       # Business logic
│       │   ├── __init__.py
│       │   ├── user_service.py
│       │   └── order_service.py
│       ├── repositories/   # Data access layer
│       │   ├── __init__.py
│       │   └── user_repo.py
│       ├── api/            # HTTP routes / CLI commands
│       │   ├── __init__.py
│       │   └── routes.py
│       └── utils/          # Shared utilities
│           ├── __init__.py
│           └── validation.py
├── tests/
│   ├── conftest.py         # Shared fixtures
│   ├── unit/
│   │   └── test_user_service.py
│   └── integration/
│       └── test_user_repo.py
├── scripts/
│   └── seed_database.py
└── docs/
    └── architecture.md</code></pre>
</section>
<section id="why-src-layout" class="level3">
<h3 class="anchored" data-anchor-id="why-src-layout">Why src-layout?</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 25%">
<col style="width: 34%">
<col style="width: 40%">
</colgroup>
<thead>
<tr class="header">
<th>Aspect</th>
<th>src-layout</th>
<th>flat-layout</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Import safety</td>
<td>Forces install before import — catches packaging bugs</td>
<td>Can accidentally import unpackaged code</td>
</tr>
<tr class="even">
<td>Namespace clarity</td>
<td><code>from mypackage.services import UserService</code></td>
<td>Same, but risk of path conflicts</td>
</tr>
<tr class="odd">
<td>CI/CD</td>
<td>Tests always run against installed package</td>
<td>May test unpackaged source</td>
</tr>
<tr class="even">
<td>Industry standard</td>
<td>Used by pip, setuptools, pytest, black</td>
<td>Legacy projects</td>
</tr>
</tbody>
</table>
</section>
<section id="key-principles" class="level3">
<h3 class="anchored" data-anchor-id="key-principles">Key Principles</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 42%">
<col style="width: 57%">
</colgroup>
<thead>
<tr class="header">
<th>Principle</th>
<th>Implementation</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>Separate concerns</strong></td>
<td>Models, services, repos, API in different directories</td>
</tr>
<tr class="even">
<td><strong>Dependency direction</strong></td>
<td><code>api → services → repositories → models</code> (never reverse)</td>
</tr>
<tr class="odd">
<td><strong>One <code>__init__.py</code> export</strong></td>
<td>Define the public API per package explicitly</td>
</tr>
<tr class="even">
<td><strong>Config from environment</strong></td>
<td><code>config.py</code> reads from env vars, not hardcoded values</td>
</tr>
<tr class="odd">
<td><strong>Tests mirror source</strong></td>
<td><code>tests/unit/test_user_service.py</code> tests <code>src/mypackage/services/user_service.py</code></td>
</tr>
</tbody>
</table>
<hr>
</section>
</section>
<section id="q2-what-are-the-solid-principles-and-how-do-they-apply-in-python" class="level2">
<h2 class="anchored" data-anchor-id="q2-what-are-the-solid-principles-and-how-do-they-apply-in-python">Q2: What are the SOLID principles and how do they apply in Python?</h2>
<p><strong>Answer:</strong></p>
<p>SOLID is a set of five design principles that produce maintainable, extensible, and testable code. While originating in Java/C#, they apply powerfully in Python.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    SOLID["SOLID Principles"]
    SOLID --&gt; S["S: Single Responsibility&lt;br/&gt;One reason to change"]
    SOLID --&gt; O["O: Open/Closed&lt;br/&gt;Open for extension, closed for modification"]
    SOLID --&gt; L["L: Liskov Substitution&lt;br/&gt;Subtypes must be substitutable"]
    SOLID --&gt; I["I: Interface Segregation&lt;br/&gt;Small, focused interfaces"]
    SOLID --&gt; D["D: Dependency Inversion&lt;br/&gt;Depend on abstractions, not concretions"]

    style SOLID fill:#56cc9d,stroke:#333,color:#fff
    style S fill:#6cc3d5,stroke:#333,color:#fff
    style O fill:#ffce67,stroke:#333
    style D fill:#ff7851,stroke:#333,color:#fff
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="s-single-responsibility-principle" class="level3">
<h3 class="anchored" data-anchor-id="s-single-responsibility-principle">S — Single Responsibility Principle</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># VIOLATION: One class does too many things</span></span>
<span id="cb2-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> UserManager:</span>
<span id="cb2-3">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> create_user(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, data): ...</span>
<span id="cb2-4">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> send_welcome_email(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, user): ...</span>
<span id="cb2-5">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> generate_report(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, users): ...</span>
<span id="cb2-6">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> export_to_csv(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, users): ...</span>
<span id="cb2-7"></span>
<span id="cb2-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># FIXED: Each class has one responsibility</span></span>
<span id="cb2-9"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> UserService:</span>
<span id="cb2-10">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> create_user(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, data): ...</span>
<span id="cb2-11"></span>
<span id="cb2-12"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> EmailService:</span>
<span id="cb2-13">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> send_welcome_email(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, user): ...</span>
<span id="cb2-14"></span>
<span id="cb2-15"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> UserReporter:</span>
<span id="cb2-16">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> generate_report(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, users): ...</span>
<span id="cb2-17">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> export_to_csv(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, users): ...</span></code></pre></div></div>
</section>
<section id="o-openclosed-principle" class="level3">
<h3 class="anchored" data-anchor-id="o-openclosed-principle">O — Open/Closed Principle</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> abc <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> ABC, abstractmethod</span>
<span id="cb3-2"></span>
<span id="cb3-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># VIOLATION: Adding a new payment method requires modifying existing code</span></span>
<span id="cb3-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> process_payment(method, amount):</span>
<span id="cb3-5">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> method <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"credit_card"</span>:</span>
<span id="cb3-6">        ...</span>
<span id="cb3-7">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">elif</span> method <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"paypal"</span>:</span>
<span id="cb3-8">        ...</span>
<span id="cb3-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">elif</span> method <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"crypto"</span>:  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Must modify this function!</span></span>
<span id="cb3-10">        ...</span>
<span id="cb3-11"></span>
<span id="cb3-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># FIXED: Open for extension (new classes), closed for modification</span></span>
<span id="cb3-13"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> PaymentProcessor(ABC):</span>
<span id="cb3-14">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@abstractmethod</span></span>
<span id="cb3-15">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> process(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, amount: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bool</span>: ...</span>
<span id="cb3-16"></span>
<span id="cb3-17"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> CreditCardProcessor(PaymentProcessor):</span>
<span id="cb3-18">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> process(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, amount: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bool</span>: ...</span>
<span id="cb3-19"></span>
<span id="cb3-20"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> PayPalProcessor(PaymentProcessor):</span>
<span id="cb3-21">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> process(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, amount: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bool</span>: ...</span>
<span id="cb3-22"></span>
<span id="cb3-23"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> CryptoProcessor(PaymentProcessor):  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Just add new class!</span></span>
<span id="cb3-24">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> process(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, amount: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bool</span>: ...</span></code></pre></div></div>
</section>
<section id="d-dependency-inversion-principle" class="level3">
<h3 class="anchored" data-anchor-id="d-dependency-inversion-principle">D — Dependency Inversion Principle</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> typing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Protocol</span>
<span id="cb4-2"></span>
<span id="cb4-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Abstraction (Protocol = duck-typed interface)</span></span>
<span id="cb4-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> UserRepository(Protocol):</span>
<span id="cb4-5">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_by_id(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, user_id: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>: ...</span>
<span id="cb4-6">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> save(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, user: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>: ...</span>
<span id="cb4-7"></span>
<span id="cb4-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># High-level module depends on abstraction, not concrete DB</span></span>
<span id="cb4-9"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> UserService:</span>
<span id="cb4-10">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, repo: UserRepository):</span>
<span id="cb4-11">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.repo <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> repo  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Injected — can be any implementation</span></span>
<span id="cb4-12"></span>
<span id="cb4-13">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_user(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, user_id: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>:</span>
<span id="cb4-14">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.repo.get_by_id(user_id)</span>
<span id="cb4-15"></span>
<span id="cb4-16"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Concrete implementations</span></span>
<span id="cb4-17"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> PostgresUserRepo:</span>
<span id="cb4-18">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_by_id(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, user_id: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>: ...</span>
<span id="cb4-19">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> save(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, user: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>: ...</span>
<span id="cb4-20"></span>
<span id="cb4-21"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> InMemoryUserRepo:  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># For testing!</span></span>
<span id="cb4-22">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb4-23">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._store <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {}</span>
<span id="cb4-24">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_by_id(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, user_id: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>:</span>
<span id="cb4-25">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._store[user_id]</span>
<span id="cb4-26">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> save(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, user: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb4-27">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._store[user[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"id"</span>]] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> user</span>
<span id="cb4-28"></span>
<span id="cb4-29"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Production</span></span>
<span id="cb4-30">service <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> UserService(PostgresUserRepo())</span>
<span id="cb4-31"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Testing</span></span>
<span id="cb4-32">service <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> UserService(InMemoryUserRepo())</span></code></pre></div></div>
<hr>
</section>
</section>
<section id="q3-what-is-dependency-injection-and-how-do-you-implement-it-in-python" class="level2">
<h2 class="anchored" data-anchor-id="q3-what-is-dependency-injection-and-how-do-you-implement-it-in-python">Q3: What is Dependency Injection and how do you implement it in Python?</h2>
<p><strong>Answer:</strong></p>
<p><strong>Dependency Injection (DI)</strong> means providing a component’s dependencies from the outside rather than having it create them internally. This makes code testable, flexible, and decoupled.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph LR
    subgraph Without["Without DI (Tight Coupling)"]
        A1["UserService"] --&gt;|"creates"| B1["PostgresDB()"]
    end

    subgraph With["With DI (Loose Coupling)"]
        A2["UserService"] --&gt;|"receives"| B2["db: Database (any impl)"]
        C2["PostgresDB"] -.-&gt;|"implements"| B2
        D2["MockDB"] -.-&gt;|"implements"| B2
    end

    style Without fill:#ff7851,stroke:#333,color:#fff
    style With fill:#56cc9d,stroke:#333,color:#fff
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="three-di-patterns-in-python" class="level3">
<h3 class="anchored" data-anchor-id="three-di-patterns-in-python">Three DI Patterns in Python</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> typing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Protocol</span>
<span id="cb5-2"></span>
<span id="cb5-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> EmailSender(Protocol):</span>
<span id="cb5-4">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> send(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, to: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>, subject: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>, body: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>: ...</span>
<span id="cb5-5"></span>
<span id="cb5-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 1. CONSTRUCTOR INJECTION (most common, recommended)</span></span>
<span id="cb5-7"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> NotificationService:</span>
<span id="cb5-8">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, email_sender: EmailSender):</span>
<span id="cb5-9">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._sender <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> email_sender</span>
<span id="cb5-10"></span>
<span id="cb5-11">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> notify_user(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, user_email: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>, message: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>):</span>
<span id="cb5-12">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._sender.send(user_email, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Notification"</span>, message)</span>
<span id="cb5-13"></span>
<span id="cb5-14"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 2. METHOD INJECTION (for one-off dependencies)</span></span>
<span id="cb5-15"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> ReportGenerator:</span>
<span id="cb5-16">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> generate(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, data: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>, formatter: Formatter) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>:</span>
<span id="cb5-17">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> formatter.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">format</span>(data)</span>
<span id="cb5-18"></span>
<span id="cb5-19"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 3. MODULE-LEVEL INJECTION (simple cases)</span></span>
<span id="cb5-20"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># config.py</span></span>
<span id="cb5-21"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_database():</span>
<span id="cb5-22">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> os.environ.get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"TESTING"</span>):</span>
<span id="cb5-23">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> InMemoryDB()</span>
<span id="cb5-24">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> PostgresDB(os.environ[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"DATABASE_URL"</span>])</span></code></pre></div></div>
</section>
<section id="wiring-dependencies-composition-root" class="level3">
<h3 class="anchored" data-anchor-id="wiring-dependencies-composition-root">Wiring Dependencies (Composition Root)</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># app.py — the "composition root" wires everything together</span></span>
<span id="cb6-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> create_app():</span>
<span id="cb6-3">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Build the dependency graph at application startup."""</span></span>
<span id="cb6-4">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Infrastructure</span></span>
<span id="cb6-5">    db <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> PostgresDatabase(settings.DATABASE_URL)</span>
<span id="cb6-6">    cache <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> RedisCache(settings.REDIS_URL)</span>
<span id="cb6-7">    email <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> SMTPEmailSender(settings.SMTP_HOST)</span>
<span id="cb6-8"></span>
<span id="cb6-9">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Repositories</span></span>
<span id="cb6-10">    user_repo <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> PostgresUserRepo(db)</span>
<span id="cb6-11">    order_repo <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> PostgresOrderRepo(db)</span>
<span id="cb6-12"></span>
<span id="cb6-13">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Services (injected with repos)</span></span>
<span id="cb6-14">    user_service <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> UserService(user_repo, cache)</span>
<span id="cb6-15">    order_service <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> OrderService(order_repo, user_service)</span>
<span id="cb6-16">    notification_service <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> NotificationService(email)</span>
<span id="cb6-17"></span>
<span id="cb6-18">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># API layer (injected with services)</span></span>
<span id="cb6-19">    app <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> FastAPI()</span>
<span id="cb6-20">    app.include_router(create_user_router(user_service))</span>
<span id="cb6-21">    app.include_router(create_order_router(order_service))</span>
<span id="cb6-22"></span>
<span id="cb6-23">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> app</span></code></pre></div></div>
</section>
<section id="testing-with-di" class="level3">
<h3 class="anchored" data-anchor-id="testing-with-di">Testing with DI</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Tests inject fakes/mocks — no real DB or email!</span></span>
<span id="cb7-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> test_notify_user():</span>
<span id="cb7-3">    fake_sender <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> FakeEmailSender()</span>
<span id="cb7-4">    service <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> NotificationService(fake_sender)</span>
<span id="cb7-5"></span>
<span id="cb7-6">    service.notify_user(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"alice@test.com"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Hello!"</span>)</span>
<span id="cb7-7"></span>
<span id="cb7-8">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> fake_sender.sent_emails <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> [</span>
<span id="cb7-9">        (<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"alice@test.com"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Notification"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Hello!"</span>)</span>
<span id="cb7-10">    ]</span></code></pre></div></div>
</section>
<section id="when-to-use-di" class="level3">
<h3 class="anchored" data-anchor-id="when-to-use-di">When to Use DI</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 36%">
<col style="width: 63%">
</colgroup>
<thead>
<tr class="header">
<th>Use DI</th>
<th>Don’t Bother</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>External services (DB, cache, APIs)</td>
<td>Pure utility functions</td>
</tr>
<tr class="even">
<td>Components you want to test in isolation</td>
<td>Simple scripts</td>
</tr>
<tr class="odd">
<td>Multiple implementations needed</td>
<td>Tight internal helpers</td>
</tr>
<tr class="even">
<td>Cross-cutting concerns (logging, metrics)</td>
<td>Leaf functions with no dependencies</td>
</tr>
</tbody>
</table>
<hr>
</section>
</section>
<section id="q4-what-are-the-most-useful-design-patterns-in-python" class="level2">
<h2 class="anchored" data-anchor-id="q4-what-are-the-most-useful-design-patterns-in-python">Q4: What are the most useful design patterns in Python?</h2>
<p><strong>Answer:</strong></p>
<p>Python’s dynamic nature and first-class functions mean many “classical” patterns (from Java/C++) are simpler or unnecessary. Here are the patterns that remain highly useful.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    DP["Useful Design Patterns in Python"]
    DP --&gt; CREAT["Creational"]
    DP --&gt; STRUCT["Structural"]
    DP --&gt; BEHAV["Behavioral"]

    CREAT --&gt; F["Factory Method"]
    CREAT --&gt; B["Builder"]
    CREAT --&gt; S["Singleton (module-level)"]

    STRUCT --&gt; A["Adapter"]
    STRUCT --&gt; D["Decorator (native!)"]
    STRUCT --&gt; FA["Facade"]

    BEHAV --&gt; ST["Strategy (functions!)"]
    BEHAV --&gt; OB["Observer"]
    BEHAV --&gt; IT["Iterator (native!)"]

    style DP fill:#56cc9d,stroke:#333,color:#fff
    style CREAT fill:#6cc3d5,stroke:#333,color:#fff
    style BEHAV fill:#ffce67,stroke:#333
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="factory-pattern" class="level3">
<h3 class="anchored" data-anchor-id="factory-pattern">Factory Pattern</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> dataclasses <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> dataclass</span>
<span id="cb8-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> typing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Literal</span>
<span id="cb8-3"></span>
<span id="cb8-4"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@dataclass</span></span>
<span id="cb8-5"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Notification:</span>
<span id="cb8-6">    message: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span></span>
<span id="cb8-7">    recipient: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span></span>
<span id="cb8-8"></span>
<span id="cb8-9"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> EmailNotification(Notification):</span>
<span id="cb8-10">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> send(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>): <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Email to </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>recipient<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>message<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb8-11"></span>
<span id="cb8-12"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> SMSNotification(Notification):</span>
<span id="cb8-13">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> send(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>): <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"SMS to </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>recipient<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>message<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb8-14"></span>
<span id="cb8-15"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> SlackNotification(Notification):</span>
<span id="cb8-16">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> send(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>): <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Slack to </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>recipient<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>message<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb8-17"></span>
<span id="cb8-18"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Factory function (Pythonic — no need for a class!)</span></span>
<span id="cb8-19"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> create_notification(</span>
<span id="cb8-20">    channel: Literal[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"email"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sms"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"slack"</span>],</span>
<span id="cb8-21">    message: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>,</span>
<span id="cb8-22">    recipient: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>,</span>
<span id="cb8-23">) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> Notification:</span>
<span id="cb8-24">    factories <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {</span>
<span id="cb8-25">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"email"</span>: EmailNotification,</span>
<span id="cb8-26">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sms"</span>: SMSNotification,</span>
<span id="cb8-27">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"slack"</span>: SlackNotification,</span>
<span id="cb8-28">    }</span>
<span id="cb8-29">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> channel <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> factories:</span>
<span id="cb8-30">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> <span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">ValueError</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Unknown channel: </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>channel<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb8-31">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> factories[channel](message<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>message, recipient<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>recipient)</span></code></pre></div></div>
</section>
<section id="strategy-pattern-just-use-functions" class="level3">
<h3 class="anchored" data-anchor-id="strategy-pattern-just-use-functions">Strategy Pattern (Just Use Functions!)</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> typing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Callable</span>
<span id="cb9-2"></span>
<span id="cb9-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># In Java you'd create a Strategy interface + concrete classes</span></span>
<span id="cb9-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># In Python: just pass a function!</span></span>
<span id="cb9-5"></span>
<span id="cb9-6"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> process_data(</span>
<span id="cb9-7">    data: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>],</span>
<span id="cb9-8">    strategy: Callable[[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>]], <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>],</span>
<span id="cb9-9">) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>:</span>
<span id="cb9-10">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> strategy(data)</span>
<span id="cb9-11"></span>
<span id="cb9-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Strategies are just functions</span></span>
<span id="cb9-13"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> mean_strategy(data: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>]) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>:</span>
<span id="cb9-14">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(data) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(data)</span>
<span id="cb9-15"></span>
<span id="cb9-16"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> median_strategy(data: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>]) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">float</span>:</span>
<span id="cb9-17">    sorted_data <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sorted</span>(data)</span>
<span id="cb9-18">    n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(sorted_data)</span>
<span id="cb9-19">    mid <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">//</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb9-20">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> sorted_data[mid] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> n <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> (sorted_data[mid<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> sorted_data[mid]) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb9-21"></span>
<span id="cb9-22"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Usage</span></span>
<span id="cb9-23">result <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> process_data([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>], strategy<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>mean_strategy)</span>
<span id="cb9-24">result <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> process_data([<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>], strategy<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>median_strategy)</span></code></pre></div></div>
</section>
<section id="observer-pattern" class="level3">
<h3 class="anchored" data-anchor-id="observer-pattern">Observer Pattern</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> typing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Callable</span>
<span id="cb10-2"></span>
<span id="cb10-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> EventBus:</span>
<span id="cb10-4">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Simple publish-subscribe event system."""</span></span>
<span id="cb10-5"></span>
<span id="cb10-6">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb10-7">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._subscribers: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>[Callable]] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {}</span>
<span id="cb10-8"></span>
<span id="cb10-9">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> subscribe(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, event: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>, callback: Callable) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb10-10">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._subscribers.setdefault(event, []).append(callback)</span>
<span id="cb10-11"></span>
<span id="cb10-12">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> publish(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, event: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>data) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb10-13">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> callback <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._subscribers.get(event, []):</span>
<span id="cb10-14">            callback(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>data)</span>
<span id="cb10-15"></span>
<span id="cb10-16"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Usage</span></span>
<span id="cb10-17">bus <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> EventBus()</span>
<span id="cb10-18">bus.subscribe(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"user_created"</span>, <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>d: send_welcome_email(d[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"email"</span>]))</span>
<span id="cb10-19">bus.subscribe(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"user_created"</span>, <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">**</span>d: log_event(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"signup"</span>, d))</span>
<span id="cb10-20">bus.publish(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"user_created"</span>, email<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"alice@example.com"</span>, name<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Alice"</span>)</span></code></pre></div></div>
</section>
<section id="singleton-python-way-module-level-instance" class="level3">
<h3 class="anchored" data-anchor-id="singleton-python-way-module-level-instance">Singleton (Python Way: Module-Level Instance)</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># DON'T use metaclass singleton in Python. Use module-level instance:</span></span>
<span id="cb11-2"></span>
<span id="cb11-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># database.py</span></span>
<span id="cb11-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> _Database:</span>
<span id="cb11-5">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">__init__</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>):</span>
<span id="cb11-6">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._connection <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span></span>
<span id="cb11-7"></span>
<span id="cb11-8">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">connect</span>(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, url: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>):</span>
<span id="cb11-9">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._connection <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> create_connection(url)</span>
<span id="cb11-10"></span>
<span id="cb11-11">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> query(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, sql: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>):</span>
<span id="cb11-12">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._connection.execute(sql)</span>
<span id="cb11-13"></span>
<span id="cb11-14"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Module-level singleton — imported by other modules</span></span>
<span id="cb11-15">db <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> _Database()</span>
<span id="cb11-16"></span>
<span id="cb11-17"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Other files:</span></span>
<span id="cb11-18"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># from mypackage.database import db</span></span>
<span id="cb11-19"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># db.query("SELECT * FROM users")</span></span></code></pre></div></div>
</section>
<section id="patterns-comparison" class="level3">
<h3 class="anchored" data-anchor-id="patterns-comparison">Patterns Comparison</h3>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Pattern</th>
<th>Java/C++ Way</th>
<th>Pythonic Way</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Singleton</td>
<td>Metaclass / <code>__new__</code></td>
<td>Module-level instance</td>
</tr>
<tr class="even">
<td>Strategy</td>
<td>Interface + classes</td>
<td>Pass a function</td>
</tr>
<tr class="odd">
<td>Iterator</td>
<td>Iterator class</td>
<td>Generator function (<code>yield</code>)</td>
</tr>
<tr class="even">
<td>Decorator</td>
<td>Wrapper class</td>
<td><code>@decorator</code> function</td>
</tr>
<tr class="odd">
<td>Observer</td>
<td>Interface + registration</td>
<td>Callbacks / signals</td>
</tr>
<tr class="even">
<td>Builder</td>
<td>Builder class</td>
<td><code>@dataclass</code> + defaults or <code>**kwargs</code></td>
</tr>
</tbody>
</table>
<hr>
</section>
</section>
<section id="q5-how-do-you-manage-configuration-and-environment-variables-properly" class="level2">
<h2 class="anchored" data-anchor-id="q5-how-do-you-manage-configuration-and-environment-variables-properly">Q5: How do you manage configuration and environment variables properly?</h2>
<p><strong>Answer:</strong></p>
<p>Production Python applications separate configuration from code, support multiple environments, validate settings at startup, and never commit secrets.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    ENV[".env file (local only)"]
    ENVVAR["OS Environment Variables&lt;br/&gt;(production)"]
    DEFAULT["Defaults in code&lt;br/&gt;(non-sensitive only)"]

    ENV --&gt; CONFIG["config.py / Settings class"]
    ENVVAR --&gt; CONFIG
    DEFAULT --&gt; CONFIG

    CONFIG --&gt; APP["Application Code"]

    style CONFIG fill:#56cc9d,stroke:#333,color:#fff
    style ENV fill:#ffce67,stroke:#333
    style ENVVAR fill:#6cc3d5,stroke:#333,color:#fff
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="pydantic-settings-recommended" class="level3">
<h3 class="anchored" data-anchor-id="pydantic-settings-recommended">Pydantic Settings (Recommended)</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># config.py</span></span>
<span id="cb12-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> pydantic_settings <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> BaseSettings</span>
<span id="cb12-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> pydantic <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Field</span>
<span id="cb12-4"></span>
<span id="cb12-5"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Settings(BaseSettings):</span>
<span id="cb12-6">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Application settings — loaded from environment variables."""</span></span>
<span id="cb12-7"></span>
<span id="cb12-8">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Required (no default = must be in env)</span></span>
<span id="cb12-9">    database_url: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span></span>
<span id="cb12-10">    secret_key: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span></span>
<span id="cb12-11"></span>
<span id="cb12-12">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Optional with defaults</span></span>
<span id="cb12-13">    debug: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bool</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span></span>
<span id="cb12-14">    log_level: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"INFO"</span></span>
<span id="cb12-15">    max_connections: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Field(default<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, ge<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, le<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>)</span>
<span id="cb12-16">    allowed_hosts: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"localhost"</span>]</span>
<span id="cb12-17"></span>
<span id="cb12-18">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Nested prefix</span></span>
<span id="cb12-19">    redis_host: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"localhost"</span></span>
<span id="cb12-20">    redis_port: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6379</span></span>
<span id="cb12-21"></span>
<span id="cb12-22">    model_config <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {</span>
<span id="cb12-23">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"env_file"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">".env"</span>,           <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Load from .env in development</span></span>
<span id="cb12-24">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"env_file_encoding"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"utf-8"</span>,</span>
<span id="cb12-25">        <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"case_sensitive"</span>: <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>,</span>
<span id="cb12-26">    }</span>
<span id="cb12-27"></span>
<span id="cb12-28"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Instantiate once at startup — validates all values</span></span>
<span id="cb12-29">settings <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Settings()</span>
<span id="cb12-30"></span>
<span id="cb12-31"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Usage elsewhere:</span></span>
<span id="cb12-32"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># from mypackage.config import settings</span></span>
<span id="cb12-33"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># db = connect(settings.database_url)</span></span></code></pre></div></div>
</section>
<section id="environment-file-structure" class="level3">
<h3 class="anchored" data-anchor-id="environment-file-structure">Environment File Structure</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb13-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># .env (local development — NEVER commit this!)</span></span>
<span id="cb13-2"><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">DATABASE_URL</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>postgresql://user:pass@localhost/mydb</span>
<span id="cb13-3"><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">SECRET_KEY</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>dev-secret-key-change-in-prod</span>
<span id="cb13-4"><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">DEBUG</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>true</span>
<span id="cb13-5"><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">LOG_LEVEL</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>DEBUG</span>
<span id="cb13-6"></span>
<span id="cb13-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># .env.example (committed — template for developers)</span></span>
<span id="cb13-8"><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">DATABASE_URL</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>postgresql://user:password@localhost/dbname</span>
<span id="cb13-9"><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">SECRET_KEY</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>change-me</span>
<span id="cb13-10"><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">DEBUG</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>false</span>
<span id="cb13-11"><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">LOG_LEVEL</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>INFO</span></code></pre></div></div>
</section>
<section id="best-practices" class="level3">
<h3 class="anchored" data-anchor-id="best-practices">Best Practices</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 66%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Practice</th>
<th>Why</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Use <code>.env</code> for local dev only</td>
<td>Secrets stay out of code and git</td>
</tr>
<tr class="even">
<td>Validate at startup (Pydantic)</td>
<td>Fail fast with clear error messages</td>
</tr>
<tr class="odd">
<td>Never use <code>os.getenv()</code> scattered everywhere</td>
<td>Centralize in one <code>config.py</code> module</td>
</tr>
<tr class="even">
<td>Add <code>.env</code> to <code>.gitignore</code></td>
<td>Prevent accidental secret commits</td>
</tr>
<tr class="odd">
<td>Commit <code>.env.example</code></td>
<td>Onboarding documentation</td>
</tr>
<tr class="even">
<td>Use different env files per environment</td>
<td><code>.env.test</code>, <code>.env.staging</code></td>
</tr>
<tr class="odd">
<td>Type all settings</td>
<td>Catch <code>"true"</code> vs <code>True</code> issues early</td>
</tr>
</tbody>
</table>
<hr>
</section>
</section>
<section id="q6-how-should-you-handle-imports-and-module-organization" class="level2">
<h2 class="anchored" data-anchor-id="q6-how-should-you-handle-imports-and-module-organization">Q6: How should you handle imports and module organization?</h2>
<p><strong>Answer:</strong></p>
<p>Clean import organization makes code navigable, prevents circular dependencies, and establishes clear module boundaries.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    subgraph ImportOrder["Import Order (PEP 8 + isort)"]
        direction TB
        I1["1. Standard library&lt;br/&gt;import os, sys, json"]
        I2["2. Third-party packages&lt;br/&gt;import fastapi, pydantic"]
        I3["3. Local application&lt;br/&gt;from mypackage.services import UserService"]
    end

    subgraph Avoid["Common Anti-Patterns"]
        A1["from module import *"]
        A2["Circular imports"]
        A3["Import inside function (usually)"]
    end

    style ImportOrder fill:#56cc9d,stroke:#333,color:#fff
    style Avoid fill:#ff7851,stroke:#333,color:#fff
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="import-best-practices" class="level3">
<h3 class="anchored" data-anchor-id="import-best-practices">Import Best Practices</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb14-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># GOOD: Clear, explicit imports in standard order</span></span>
<span id="cb14-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> os</span>
<span id="cb14-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> sys</span>
<span id="cb14-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> pathlib <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Path</span>
<span id="cb14-5"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> typing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Protocol</span>
<span id="cb14-6"></span>
<span id="cb14-7"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> httpx</span>
<span id="cb14-8"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> fastapi <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> FastAPI, Depends</span>
<span id="cb14-9"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> pydantic <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> BaseModel</span>
<span id="cb14-10"></span>
<span id="cb14-11"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> mypackage.config <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> settings</span>
<span id="cb14-12"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> mypackage.models.user <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> User</span>
<span id="cb14-13"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> mypackage.services.user_service <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> UserService</span></code></pre></div></div>
</section>
<section id="controlling-public-api-with-__init__.py" class="level3">
<h3 class="anchored" data-anchor-id="controlling-public-api-with-__init__.py">Controlling Public API with <code>__init__.py</code></h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb15-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># mypackage/models/__init__.py</span></span>
<span id="cb15-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Expose only the public API of this subpackage."""</span></span>
<span id="cb15-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> mypackage.models.user <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> User, UserCreate, UserUpdate</span>
<span id="cb15-4"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> mypackage.models.order <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Order, OrderStatus</span>
<span id="cb15-5"></span>
<span id="cb15-6"><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">__all__</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"User"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"UserCreate"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"UserUpdate"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Order"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"OrderStatus"</span>]</span>
<span id="cb15-7"></span>
<span id="cb15-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Now consumers use clean imports:</span></span>
<span id="cb15-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># from mypackage.models import User, Order</span></span>
<span id="cb15-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># (not: from mypackage.models.user import User)</span></span></code></pre></div></div>
</section>
<section id="solving-circular-imports" class="level3">
<h3 class="anchored" data-anchor-id="solving-circular-imports">Solving Circular Imports</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb16-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># PROBLEM: A imports B, B imports A</span></span>
<span id="cb16-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># services/user_service.py</span></span>
<span id="cb16-3"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> mypackage.services.order_service <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> OrderService  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Circular!</span></span>
<span id="cb16-4"></span>
<span id="cb16-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># SOLUTION 1: Import inside method (deferred import)</span></span>
<span id="cb16-6"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> UserService:</span>
<span id="cb16-7">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_user_orders(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, user_id: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>):</span>
<span id="cb16-8">        <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> mypackage.services.order_service <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> OrderService</span>
<span id="cb16-9">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> OrderService().get_orders_for(user_id)</span>
<span id="cb16-10"></span>
<span id="cb16-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># SOLUTION 2: Use TYPE_CHECKING for type hints only</span></span>
<span id="cb16-12"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> __future__ <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> annotations</span>
<span id="cb16-13"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> typing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> TYPE_CHECKING</span>
<span id="cb16-14"></span>
<span id="cb16-15"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> TYPE_CHECKING:</span>
<span id="cb16-16">    <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> mypackage.services.order_service <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> OrderService</span>
<span id="cb16-17"></span>
<span id="cb16-18"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> UserService:</span>
<span id="cb16-19">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_user_orders(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, order_service: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"OrderService"</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>: ...</span>
<span id="cb16-20"></span>
<span id="cb16-21"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># SOLUTION 3 (best): Restructure to eliminate the cycle</span></span>
<span id="cb16-22"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Extract shared interface into a separate module</span></span></code></pre></div></div>
</section>
<section id="module-organization-rules" class="level3">
<h3 class="anchored" data-anchor-id="module-organization-rules">Module Organization Rules</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 40%">
<col style="width: 60%">
</colgroup>
<thead>
<tr class="header">
<th>Rule</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>One class per file (for major classes)</td>
<td><code>user_service.py</code> contains <code>UserService</code></td>
</tr>
<tr class="even">
<td>Related small classes can share a file</td>
<td><code>exceptions.py</code> with all custom exceptions</td>
</tr>
<tr class="odd">
<td><code>__init__.py</code> defines public API</td>
<td>Import and re-export key names</td>
</tr>
<tr class="even">
<td>Private helpers prefixed with <code>_</code></td>
<td><code>_validate_email()</code> not exported</td>
</tr>
<tr class="odd">
<td>Constants in dedicated module</td>
<td><code>constants.py</code> or <code>enums.py</code></td>
</tr>
</tbody>
</table>
<hr>
</section>
</section>
<section id="q7-what-are-abstract-base-classes-abcs-and-protocols-and-when-do-you-use-each" class="level2">
<h2 class="anchored" data-anchor-id="q7-what-are-abstract-base-classes-abcs-and-protocols-and-when-do-you-use-each">Q7: What are Abstract Base Classes (ABCs) and Protocols, and when do you use each?</h2>
<p><strong>Answer:</strong></p>
<p>Both ABCs and Protocols define <strong>interfaces</strong> (expected method signatures), but they differ in how they enforce compliance.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph LR
    subgraph ABC_Side["ABC (Nominal Typing)"]
        ABC1["Must explicitly inherit"]
        ABC2["Fails at instantiation&lt;br/&gt;if method missing"]
        ABC3["isinstance() works"]
    end

    subgraph Protocol_Side["Protocol (Structural Typing)"]
        P1["No inheritance needed"]
        P2["Fails at type-check time&lt;br/&gt;(mypy/pyright)"]
        P3["Duck typing with safety"]
    end

    style ABC_Side fill:#6cc3d5,stroke:#333,color:#fff
    style Protocol_Side fill:#56cc9d,stroke:#333,color:#fff
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="abc-explicit-contract" class="level3">
<h3 class="anchored" data-anchor-id="abc-explicit-contract">ABC: Explicit Contract</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb17-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> abc <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> ABC, abstractmethod</span>
<span id="cb17-2"></span>
<span id="cb17-3"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Repository(ABC):</span>
<span id="cb17-4">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""All repositories MUST implement these methods."""</span></span>
<span id="cb17-5"></span>
<span id="cb17-6">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@abstractmethod</span></span>
<span id="cb17-7">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">id</span>: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>:</span>
<span id="cb17-8">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Retrieve an entity by ID."""</span></span>
<span id="cb17-9">        ...</span>
<span id="cb17-10"></span>
<span id="cb17-11">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@abstractmethod</span></span>
<span id="cb17-12">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> save(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, entity: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb17-13">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Persist an entity."""</span></span>
<span id="cb17-14">        ...</span>
<span id="cb17-15"></span>
<span id="cb17-16">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@abstractmethod</span></span>
<span id="cb17-17">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> delete(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">id</span>: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb17-18">        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"""Remove an entity."""</span></span>
<span id="cb17-19">        ...</span>
<span id="cb17-20"></span>
<span id="cb17-21"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Must inherit AND implement all abstract methods</span></span>
<span id="cb17-22"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> UserRepository(Repository):</span>
<span id="cb17-23">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">id</span>: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>:</span>
<span id="cb17-24">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._db.fetch_one(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">id</span>)</span>
<span id="cb17-25"></span>
<span id="cb17-26">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> save(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, entity: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb17-27">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._db.upsert(entity)</span>
<span id="cb17-28"></span>
<span id="cb17-29">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> delete(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">id</span>: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb17-30">        <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._db.remove(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">id</span>)</span>
<span id="cb17-31"></span>
<span id="cb17-32"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># This would raise TypeError at instantiation:</span></span>
<span id="cb17-33"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># class BadRepo(Repository):</span></span>
<span id="cb17-34"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#     def get(self, id): ...</span></span>
<span id="cb17-35"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">#     # Missing save() and delete()!</span></span>
<span id="cb17-36"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># BadRepo()  # TypeError!</span></span></code></pre></div></div>
</section>
<section id="protocol-structural-duck-typing" class="level3">
<h3 class="anchored" data-anchor-id="protocol-structural-duck-typing">Protocol: Structural (Duck) Typing</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb18-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> typing <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> Protocol, runtime_checkable</span>
<span id="cb18-2"></span>
<span id="cb18-3"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@runtime_checkable</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Optional: enables isinstance() checks</span></span>
<span id="cb18-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Serializable(Protocol):</span>
<span id="cb18-5">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> to_dict(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>: ...</span>
<span id="cb18-6">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> from_dict(cls, data: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Serializable"</span>: ...</span>
<span id="cb18-7"></span>
<span id="cb18-8"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># No inheritance needed — just implement the methods!</span></span>
<span id="cb18-9"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> User:</span>
<span id="cb18-10">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> to_dict(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>:</span>
<span id="cb18-11">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"name"</span>: <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.name, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"email"</span>: <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>.email}</span>
<span id="cb18-12"></span>
<span id="cb18-13">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@classmethod</span></span>
<span id="cb18-14">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> from_dict(cls, data: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"User"</span>:</span>
<span id="cb18-15">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> cls(name<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>data[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"name"</span>], email<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>data[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"email"</span>])</span>
<span id="cb18-16"></span>
<span id="cb18-17"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># User satisfies the Serializable protocol without inheriting it</span></span>
<span id="cb18-18"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> serialize(obj: Serializable) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>:</span>
<span id="cb18-19">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> obj.to_dict()</span>
<span id="cb18-20"></span>
<span id="cb18-21">serialize(User(...))  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Works! mypy verifies User has to_dict()</span></span></code></pre></div></div>
</section>
<section id="when-to-use-each" class="level3">
<h3 class="anchored" data-anchor-id="when-to-use-each">When to Use Each</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 40%">
<col style="width: 59%">
</colgroup>
<thead>
<tr class="header">
<th>Use ABC</th>
<th>Use Protocol</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Framework/library defining a plugin interface</td>
<td>Type hints for duck-typed code</td>
</tr>
<tr class="even">
<td>Need runtime <code>isinstance()</code> checks</td>
<td>Third-party classes you can’t modify</td>
</tr>
<tr class="odd">
<td>Want immediate error on missing methods</td>
<td>Simpler, no inheritance needed</td>
</tr>
<tr class="even">
<td>Internal code with clear hierarchy</td>
<td>Cross-boundary interfaces</td>
</tr>
<tr class="odd">
<td>Small teams where inheritance is acceptable</td>
<td>Large codebases valuing flexibility</td>
</tr>
</tbody>
</table>
<hr>
</section>
</section>
<section id="q8-what-are-pythons-code-quality-tools-and-how-should-they-be-configured" class="level2">
<h2 class="anchored" data-anchor-id="q8-what-are-pythons-code-quality-tools-and-how-should-they-be-configured">Q8: What are Python’s code quality tools and how should they be configured?</h2>
<p><strong>Answer:</strong></p>
<p>Modern Python projects use a <strong>layered toolchain</strong> for formatting, linting, type checking, and security scanning — all automated in CI/CD.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph LR
    CODE["Source Code"]
    CODE --&gt; FORMAT["Formatter&lt;br/&gt;ruff format / black"]
    FORMAT --&gt; LINT["Linter&lt;br/&gt;ruff check"]
    LINT --&gt; TYPE["Type Checker&lt;br/&gt;mypy / pyright"]
    TYPE --&gt; SEC["Security&lt;br/&gt;bandit / safety"]
    SEC --&gt; TEST["Tests&lt;br/&gt;pytest"]

    style CODE fill:#56cc9d,stroke:#333,color:#fff
    style FORMAT fill:#6cc3d5,stroke:#333,color:#fff
    style LINT fill:#ffce67,stroke:#333
    style TYPE fill:#ff7851,stroke:#333,color:#fff
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="recommended-toolchain-2026" class="level3">
<h3 class="anchored" data-anchor-id="recommended-toolchain-2026">Recommended Toolchain (2026)</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 27%">
<col style="width: 40%">
<col style="width: 31%">
</colgroup>
<thead>
<tr class="header">
<th>Tool</th>
<th>Purpose</th>
<th>Speed</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>ruff</strong></td>
<td>Linting + formatting (replaces flake8, isort, black)</td>
<td>Extremely fast (Rust)</td>
</tr>
<tr class="even">
<td><strong>mypy</strong> or <strong>pyright</strong></td>
<td>Static type checking</td>
<td>mypy: thorough; pyright: fast</td>
</tr>
<tr class="odd">
<td><strong>pytest</strong></td>
<td>Testing</td>
<td>—</td>
</tr>
<tr class="even">
<td><strong>pre-commit</strong></td>
<td>Run checks before each commit</td>
<td>—</td>
</tr>
<tr class="odd">
<td><strong>bandit</strong></td>
<td>Security vulnerability scanning</td>
<td>—</td>
</tr>
</tbody>
</table>
</section>
<section id="pyproject.toml-configuration" class="level3">
<h3 class="anchored" data-anchor-id="pyproject.toml-configuration"><code>pyproject.toml</code> Configuration</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode toml code-with-copy"><code class="sourceCode toml"><span id="cb19-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">[tool.ruff]</span></span>
<span id="cb19-2"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">target-version</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"py312"</span></span>
<span id="cb19-3"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">line-length</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">88</span></span>
<span id="cb19-4"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">src</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"src"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span></span>
<span id="cb19-5"></span>
<span id="cb19-6"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">[tool.ruff.lint]</span></span>
<span id="cb19-7"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">select</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span></span>
<span id="cb19-8">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"E"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span>    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># pycodestyle errors</span></span>
<span id="cb19-9">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"W"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span>    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># pycodestyle warnings</span></span>
<span id="cb19-10">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"F"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span>    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># pyflakes</span></span>
<span id="cb19-11">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"I"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span>    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># isort (import sorting)</span></span>
<span id="cb19-12">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"N"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span>    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># pep8-naming</span></span>
<span id="cb19-13">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"UP"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span>   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># pyupgrade (modern syntax)</span></span>
<span id="cb19-14">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"B"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span>    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># bugbear (common bugs)</span></span>
<span id="cb19-15">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"SIM"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># simplify</span></span>
<span id="cb19-16">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"RUF"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ruff-specific rules</span></span>
<span id="cb19-17"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span></span>
<span id="cb19-18"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">ignore</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"E501"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Line length handled by formatter</span></span>
<span id="cb19-19"></span>
<span id="cb19-20"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">[tool.ruff.lint.isort]</span></span>
<span id="cb19-21"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">known-first-party</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mypackage"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span></span>
<span id="cb19-22"></span>
<span id="cb19-23"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">[tool.mypy]</span></span>
<span id="cb19-24"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">python_version</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3.12"</span></span>
<span id="cb19-25"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">strict</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">true</span></span>
<span id="cb19-26"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">warn_return_any</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">true</span></span>
<span id="cb19-27"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">warn_unused_configs</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">true</span></span>
<span id="cb19-28"></span>
<span id="cb19-29"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">[[tool.mypy.overrides]]</span></span>
<span id="cb19-30"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">module</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tests.*"</span></span>
<span id="cb19-31"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">disallow_untyped_defs</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">false</span></span>
<span id="cb19-32"></span>
<span id="cb19-33"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">[tool.pytest.ini_options]</span></span>
<span id="cb19-34"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">testpaths</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tests"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span></span>
<span id="cb19-35"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">addopts</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"-v --tb=short --strict-markers"</span></span>
<span id="cb19-36"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">markers</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span></span>
<span id="cb19-37">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"slow: marks tests as slow"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb19-38">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"integration: marks integration tests"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb19-39"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span></span></code></pre></div></div>
</section>
<section id="makefile-for-common-commands" class="level3">
<h3 class="anchored" data-anchor-id="makefile-for-common-commands">Makefile for Common Commands</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb20" style="background: #f1f3f5;"><pre class="sourceCode makefile code-with-copy"><code class="sourceCode makefile"><span id="cb20-1"><span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">.PHONY:</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;"> lint format type-check test all</span></span>
<span id="cb20-2"></span>
<span id="cb20-3"><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">lint:</span></span>
<span id="cb20-4"><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">    </span>ruff check src/ tests/</span>
<span id="cb20-5"></span>
<span id="cb20-6"><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">format:</span></span>
<span id="cb20-7"><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">    </span>ruff format src/ tests/</span>
<span id="cb20-8"></span>
<span id="cb20-9"><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">type-check:</span></span>
<span id="cb20-10"><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">    </span>mypy src/</span>
<span id="cb20-11"></span>
<span id="cb20-12"><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">test:</span></span>
<span id="cb20-13"><span class="er" style="color: #AD0000;
background-color: null;
font-style: inherit;">    </span>pytest tests/ -v</span>
<span id="cb20-14"></span>
<span id="cb20-15"><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">all:</span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;"> format lint type-check test</span></span></code></pre></div></div>
</section>
<section id="pre-commit-configuration" class="level3">
<h3 class="anchored" data-anchor-id="pre-commit-configuration">Pre-commit Configuration</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode yaml code-with-copy"><code class="sourceCode yaml"><span id="cb21-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># .pre-commit-config.yaml</span></span>
<span id="cb21-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">repos</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span></span>
<span id="cb21-3"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">  </span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">-</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">repo</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> https://github.com/astral-sh/ruff-pre-commit</span></span>
<span id="cb21-4"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">    </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rev</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> v0.8.0</span></span>
<span id="cb21-5"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">    </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">hooks</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span></span>
<span id="cb21-6"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">      </span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">-</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">id</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> ruff</span></span>
<span id="cb21-7"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">        </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">args</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">[</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--fix</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">]</span></span>
<span id="cb21-8"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">      </span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">-</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">id</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> ruff-format</span></span>
<span id="cb21-9"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">  </span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">-</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">repo</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> https://github.com/pre-commit/mirrors-mypy</span></span>
<span id="cb21-10"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">    </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rev</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> v1.13.0</span></span>
<span id="cb21-11"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">    </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">hooks</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span></span>
<span id="cb21-12"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">      </span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">-</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">id</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> mypy</span></span>
<span id="cb21-13"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">        </span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">additional_dependencies</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">:</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;"> </span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">[</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">pydantic</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">]</span></span></code></pre></div></div>
<hr>
</section>
</section>
<section id="q9-how-do-you-handle-errors-and-logging-in-production-python-code" class="level2">
<h2 class="anchored" data-anchor-id="q9-how-do-you-handle-errors-and-logging-in-production-python-code">Q9: How do you handle errors and logging in production Python code?</h2>
<p><strong>Answer:</strong></p>
<p>Production code needs <strong>structured logging</strong> (not print statements) and <strong>layered error handling</strong> that provides context for debugging without exposing internals to users.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    subgraph Logging["Structured Logging"]
        L1["DEBUG: Detailed diagnostic info"]
        L2["INFO: Normal operations"]
        L3["WARNING: Unexpected but handled"]
        L4["ERROR: Failed operations"]
        L5["CRITICAL: System failure"]
    end

    subgraph ErrorFlow["Error Handling Layers"]
        E1["Repository: raise specific errors"]
        E2["Service: catch, add context, re-raise"]
        E3["API: catch all, return user-friendly response"]
    end

    style Logging fill:#56cc9d,stroke:#333,color:#fff
    style ErrorFlow fill:#6cc3d5,stroke:#333,color:#fff
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="structured-logging-setup" class="level3">
<h3 class="anchored" data-anchor-id="structured-logging-setup">Structured Logging Setup</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb22" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb22-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> logging</span>
<span id="cb22-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> structlog</span>
<span id="cb22-3"></span>
<span id="cb22-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Configure structlog for JSON output (production)</span></span>
<span id="cb22-5">structlog.configure(</span>
<span id="cb22-6">    processors<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[</span>
<span id="cb22-7">        structlog.contextvars.merge_contextvars,</span>
<span id="cb22-8">        structlog.processors.add_log_level,</span>
<span id="cb22-9">        structlog.processors.TimeStamper(fmt<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"iso"</span>),</span>
<span id="cb22-10">        structlog.processors.JSONRenderer(),  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># JSON in prod</span></span>
<span id="cb22-11">    ],</span>
<span id="cb22-12">    logger_factory<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>structlog.stdlib.LoggerFactory(),</span>
<span id="cb22-13">)</span>
<span id="cb22-14"></span>
<span id="cb22-15">logger <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> structlog.get_logger()</span>
<span id="cb22-16"></span>
<span id="cb22-17"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Usage — structured key-value pairs, not f-strings!</span></span>
<span id="cb22-18">logger.info(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"user_created"</span>, user_id<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">123</span>, email<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"alice@example.com"</span>)</span>
<span id="cb22-19"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Output: {"event": "user_created", "user_id": 123, "email": "alice@...", "level": "info", "timestamp": "..."}</span></span>
<span id="cb22-20"></span>
<span id="cb22-21">logger.error(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"payment_failed"</span>, order_id<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">456</span>, error<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"insufficient_funds"</span>, amount<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">99.99</span>)</span></code></pre></div></div>
</section>
<section id="layered-error-handling-pattern" class="level3">
<h3 class="anchored" data-anchor-id="layered-error-handling-pattern">Layered Error Handling Pattern</h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb23" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb23-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Layer 1: Repository — specific, technical errors</span></span>
<span id="cb23-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> UserRepository:</span>
<span id="cb23-3">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_by_id(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, user_id: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> User:</span>
<span id="cb23-4">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">try</span>:</span>
<span id="cb23-5">            row <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._db.fetch_one(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"SELECT * FROM users WHERE id = </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%s</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>, user_id)</span>
<span id="cb23-6">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">except</span> DatabaseError <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> e:</span>
<span id="cb23-7">            logger.error(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"db_query_failed"</span>, user_id<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>user_id, error<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>(e))</span>
<span id="cb23-8">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> RepositoryError(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Failed to fetch user </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>user_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> e</span>
<span id="cb23-9">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> row:</span>
<span id="cb23-10">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> NotFoundError(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"User </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>user_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> not found"</span>)</span>
<span id="cb23-11">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> User.from_row(row)</span>
<span id="cb23-12"></span>
<span id="cb23-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Layer 2: Service — business logic errors with context</span></span>
<span id="cb23-14"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> UserService:</span>
<span id="cb23-15">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_user_profile(<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>, user_id: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> UserProfile:</span>
<span id="cb23-16">        user <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._repo.get_by_id(user_id)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># May raise NotFoundError</span></span>
<span id="cb23-17">        orders <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">self</span>._order_repo.get_by_user(user_id)</span>
<span id="cb23-18">        logger.info(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"profile_loaded"</span>, user_id<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>user_id, order_count<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(orders))</span>
<span id="cb23-19">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> UserProfile(user<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>user, orders<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>orders)</span>
<span id="cb23-20"></span>
<span id="cb23-21"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Layer 3: API — user-friendly responses, no internal details</span></span>
<span id="cb23-22"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@app.get</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/users/</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{user_id}</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>)</span>
<span id="cb23-23"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_user(user_id: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>):</span>
<span id="cb23-24">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">try</span>:</span>
<span id="cb23-25">        profile <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> user_service.get_user_profile(user_id)</span>
<span id="cb23-26">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> profile.to_response()</span>
<span id="cb23-27">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">except</span> NotFoundError:</span>
<span id="cb23-28">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> HTTPException(status_code<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">404</span>, detail<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"User not found"</span>)</span>
<span id="cb23-29">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">except</span> RepositoryError:</span>
<span id="cb23-30">        logger.exception(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"unexpected_error"</span>, user_id<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>user_id)</span>
<span id="cb23-31">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">raise</span> HTTPException(status_code<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">500</span>, detail<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Internal server error"</span>)</span></code></pre></div></div>
</section>
<section id="logging-best-practices" class="level3">
<h3 class="anchored" data-anchor-id="logging-best-practices">Logging Best Practices</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 66%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Practice</th>
<th>Why</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Use structured logging (key-value), not f-strings</td>
<td>Machine-parseable, searchable</td>
</tr>
<tr class="even">
<td>Log at boundaries (API entry, DB calls, external APIs)</td>
<td>Trace request flow</td>
</tr>
<tr class="odd">
<td>Include request/correlation IDs</td>
<td>Connect logs across services</td>
</tr>
<tr class="even">
<td>Never log secrets (passwords, tokens, PII)</td>
<td>Security compliance</td>
</tr>
<tr class="odd">
<td>Use <code>logger.exception()</code> for unexpected errors</td>
<td>Includes full traceback</td>
</tr>
<tr class="even">
<td>Set log level via config (not code changes)</td>
<td>Adjust verbosity without deploy</td>
</tr>
</tbody>
</table>
<hr>
</section>
</section>
<section id="q10-how-do-you-package-and-distribute-a-python-project" class="level2">
<h2 class="anchored" data-anchor-id="q10-how-do-you-package-and-distribute-a-python-project">Q10: How do you package and distribute a Python project?</h2>
<p><strong>Answer:</strong></p>
<p>Modern Python packaging uses <code>pyproject.toml</code> as the single source of truth for metadata, dependencies, build configuration, and tool settings.</p>
<div class="cell" data-layout-align="default">
<div class="cell-output-display">
<div>
<p></p><figure class="figure"><p></p>
<div>
<pre class="mermaid mermaid-js">graph TD
    PYPROJ["pyproject.toml&lt;br/&gt;Single config file"]
    PYPROJ --&gt; META["Metadata&lt;br/&gt;name, version, description"]
    PYPROJ --&gt; DEPS["Dependencies&lt;br/&gt;runtime + dev groups"]
    PYPROJ --&gt; BUILD["Build System&lt;br/&gt;hatchling, setuptools, flit"]
    PYPROJ --&gt; TOOLS["Tool Config&lt;br/&gt;ruff, mypy, pytest"]

    BUILD --&gt; DIST["Distribution"]
    DIST --&gt; WHEEL["wheel (.whl)&lt;br/&gt;Binary, fast install"]
    DIST --&gt; SDIST["sdist (.tar.gz)&lt;br/&gt;Source archive"]

    style PYPROJ fill:#56cc9d,stroke:#333,color:#fff
    style BUILD fill:#6cc3d5,stroke:#333,color:#fff
    style DIST fill:#ffce67,stroke:#333
</pre>
</div>
<p></p></figure><p></p>
</div>
</div>
</div>
<section id="complete-pyproject.toml" class="level3">
<h3 class="anchored" data-anchor-id="complete-pyproject.toml">Complete <code>pyproject.toml</code></h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb24" style="background: #f1f3f5;"><pre class="sourceCode toml code-with-copy"><code class="sourceCode toml"><span id="cb24-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">[build-system]</span></span>
<span id="cb24-2"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">requires</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"hatchling"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span></span>
<span id="cb24-3"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">build-backend</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"hatchling.build"</span></span>
<span id="cb24-4"></span>
<span id="cb24-5"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">[project]</span></span>
<span id="cb24-6"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">name</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mypackage"</span></span>
<span id="cb24-7"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">version</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1.2.0"</span></span>
<span id="cb24-8"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">description</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"A well-structured Python application"</span></span>
<span id="cb24-9"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">readme</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"README.md"</span></span>
<span id="cb24-10"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">license</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"MIT"</span></span>
<span id="cb24-11"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">requires-python</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"&gt;=3.11"</span></span>
<span id="cb24-12"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">authors</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span></span>
<span id="cb24-13">    <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{ </span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">name</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"> =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Alice Smith"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">, </span><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">email</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"> =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"alice@example.com"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"> },</span></span>
<span id="cb24-14"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span></span>
<span id="cb24-15"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">dependencies</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span></span>
<span id="cb24-16">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fastapi&gt;=0.100"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb24-17">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pydantic&gt;=2.0"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb24-18">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"httpx&gt;=0.25"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb24-19">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"structlog&gt;=23.0"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb24-20"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span></span>
<span id="cb24-21"></span>
<span id="cb24-22"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">[project.optional-dependencies]</span></span>
<span id="cb24-23"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">dev</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span></span>
<span id="cb24-24">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pytest&gt;=7.0"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb24-25">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pytest-cov&gt;=4.0"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb24-26">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ruff&gt;=0.5"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb24-27">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mypy&gt;=1.10"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb24-28">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pre-commit&gt;=3.0"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span></span>
<span id="cb24-29"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span></span>
<span id="cb24-30"></span>
<span id="cb24-31"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">[project.scripts]</span></span>
<span id="cb24-32"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">mypackage</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mypackage.main:cli"</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># CLI entry point</span></span>
<span id="cb24-33"></span>
<span id="cb24-34"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">[tool.hatch.build.targets.wheel]</span></span>
<span id="cb24-35"><span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">packages</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"src/mypackage"</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span></span></code></pre></div></div>
</section>
<section id="dependency-management-with-uv" class="level3">
<h3 class="anchored" data-anchor-id="dependency-management-with-uv">Dependency Management with <code>uv</code></h3>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb25" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb25-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Modern Python package manager (replaces pip + venv + pip-tools)</span></span>
<span id="cb25-2"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">uv</span> init myproject           <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Create new project</span></span>
<span id="cb25-3"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">uv</span> add fastapi pydantic     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Add dependencies</span></span>
<span id="cb25-4"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">uv</span> add <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--dev</span> pytest ruff    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Add dev dependencies</span></span>
<span id="cb25-5"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">uv</span> sync                     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Install all dependencies</span></span>
<span id="cb25-6"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">uv</span> run pytest               <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Run in project environment</span></span>
<span id="cb25-7"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">uv</span> lock                     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Generate lockfile for reproducibility</span></span></code></pre></div></div>
</section>
<section id="versioning-and-release" class="level3">
<h3 class="anchored" data-anchor-id="versioning-and-release">Versioning and Release</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 44%">
<col style="width: 55%">
</colgroup>
<thead>
<tr class="header">
<th>Aspect</th>
<th>Practice</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Version scheme</td>
<td>Semantic versioning: <code>MAJOR.MINOR.PATCH</code></td>
</tr>
<tr class="even">
<td>Changelog</td>
<td><code>CHANGELOG.md</code> with Keep a Changelog format</td>
</tr>
<tr class="odd">
<td>Lockfile</td>
<td><code>uv.lock</code> or <code>requirements.lock</code> for reproducible installs</td>
</tr>
<tr class="even">
<td>Publishing</td>
<td><code>uv publish</code> or <code>twine upload</code> to PyPI</td>
</tr>
<tr class="odd">
<td>CI/CD</td>
<td>Automated: lint → test → build → publish on tag</td>
</tr>
</tbody>
</table>
</section>
<section id="key-principles-1" class="level3">
<h3 class="anchored" data-anchor-id="key-principles-1">Key Principles</h3>
<table class="caption-top table">
<colgroup>
<col style="width: 42%">
<col style="width: 57%">
</colgroup>
<thead>
<tr class="header">
<th>Principle</th>
<th>Implementation</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>Single source of truth</strong></td>
<td>All config in <code>pyproject.toml</code> (no <code>setup.py</code>, <code>setup.cfg</code>)</td>
</tr>
<tr class="even">
<td><strong>Pin in lockfile, range in pyproject</strong></td>
<td><code>pyproject.toml</code>: <code>fastapi&gt;=0.100</code>; lockfile pins exact versions</td>
</tr>
<tr class="odd">
<td><strong>Separate dev from runtime deps</strong></td>
<td><code>[project.optional-dependencies] dev = [...]</code></td>
</tr>
<tr class="even">
<td><strong>Reproducible builds</strong></td>
<td>Lockfile + Python version constraint</td>
</tr>
<tr class="odd">
<td><strong>Entry points</strong></td>
<td><code>[project.scripts]</code> for CLI commands</td>
</tr>
</tbody>
</table>
<hr>
</section>
</section>
<section id="summary-table" class="level2">
<h2 class="anchored" data-anchor-id="summary-table">Summary Table</h2>
<table class="caption-top table">
<colgroup>
<col style="width: 13%">
<col style="width: 30%">
<col style="width: 56%">
</colgroup>
<thead>
<tr class="header">
<th>#</th>
<th>Topic</th>
<th>Key Concept</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>1</td>
<td>Project Structure</td>
<td>src-layout; separate models/services/repos/api; tests mirror source</td>
</tr>
<tr class="even">
<td>2</td>
<td>SOLID Principles</td>
<td>SRP, Open/Closed, Liskov, Interface Segregation, Dependency Inversion</td>
</tr>
<tr class="odd">
<td>3</td>
<td>Dependency Injection</td>
<td>Constructor injection; composition root wires dependencies; enables testing</td>
</tr>
<tr class="even">
<td>4</td>
<td>Design Patterns</td>
<td>Factory, Strategy (use functions!), Observer, module-level Singleton</td>
</tr>
<tr class="odd">
<td>5</td>
<td>Configuration</td>
<td>Pydantic Settings from env vars; <code>.env</code> for dev; validate at startup</td>
</tr>
<tr class="even">
<td>6</td>
<td>Imports &amp; Modules</td>
<td>PEP 8 order; <code>__init__.py</code> for public API; avoid circular imports</td>
</tr>
<tr class="odd">
<td>7</td>
<td>ABCs vs Protocols</td>
<td>ABC for explicit inheritance; Protocol for structural duck typing</td>
</tr>
<tr class="even">
<td>8</td>
<td>Code Quality Tools</td>
<td>ruff (lint+format), mypy (types), pytest (tests), pre-commit (automation)</td>
</tr>
<tr class="odd">
<td>9</td>
<td>Logging &amp; Errors</td>
<td>Structured logging (structlog); layered error handling; no print()</td>
</tr>
<tr class="even">
<td>10</td>
<td>Packaging</td>
<td><code>pyproject.toml</code> single config; uv for deps; semantic versioning</td>
</tr>
</tbody>
</table>
<hr>
</section>
<section id="whats-next" class="level2">
<h2 class="anchored" data-anchor-id="whats-next">What’s Next?</h2>
<p>This article covered production code practices and architecture. For related content:</p>
<ul>
<li><strong>Python fundamentals:</strong> <a href="../../posts/python-swe-interview/Python-SWE-Interview-QA-1.html">Python SWE Interview QA - 1</a></li>
<li><strong>Advanced internals:</strong> <a href="../../posts/python-swe-interview/Python-SWE-Interview-QA-2.html">Python SWE Interview QA - 2</a></li>
<li><strong>Machine learning concepts:</strong> <a href="../../posts/ml-interview/ML-Interview-QA-1.html">ML Interview QA - 1</a> and <a href="../../posts/ml-interview/ML-Interview-QA-2.html">ML Interview QA - 2</a></li>
<li><strong>LLM architecture:</strong> <a href="../../posts/llm-interview/LLM-Interview-QA-1.html">LLM Interview QA - 1</a></li>
<li><strong>LLM configuration and decoding:</strong> <a href="../../posts/llm-interview/LLM-Interview-QA-3.html">LLM Interview QA - 3</a></li>
</ul>


</section>

 ]]></description>
  <guid>https://vectoringai.com/posts/swe-interview/Python-SWE-Interview-QA-3.html</guid>
  <pubDate>Wed, 20 May 2026 00:00:00 GMT</pubDate>
  <media:content url="https://vectoringai.com/images/python-swe-interview/thumb_python_swe_interview_qa_300.png" medium="image" type="image/png" height="96" width="144"/>
</item>
</channel>
</rss>
