<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Coder Legion - Recent posts tagged python3</title>
<link>https://coderlegion.com/tag/python3</link>
<description>Powered by Question2Answer</description>
<item>
<title>py_cpp_pair</title>
<link>https://coderlegion.com/17513/pycpppair</link>
<description>&lt;h2 id=&quot;py-cpp-pair&quot;&gt;py_cpp_pair&lt;/h2&gt;
&lt;p&gt;Write C++ directly inside Python strings, auto-generate &lt;code&gt;pybind11&lt;/code&gt; bindings, compile on-demand, dynamically load the extension, and inject exported symbols into your Python globals.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Version:&lt;/strong&gt; &lt;code&gt;1.0.0&lt;/code&gt;&lt;/p&gt;
&lt;h3 id=&quot;badges&quot;&gt;Badges&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;PyPI: &lt;code&gt;py_cpp_pair 1.0.0&lt;/code&gt; (import name: &lt;code&gt;py_cpp&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;Python: 3.10–3.13&lt;/li&gt;
&lt;li&gt;Platforms: Windows / Linux / macOS&lt;/li&gt;
&lt;li&gt;CI: GitHub Actions&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;install&quot;&gt;Install&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;pip install py-cpp-pair
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Import name stays:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import py_cpp as pcp
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;quickstart&quot;&gt;Quickstart&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import py_cpp as pcp

pcp.cpp(&quot;&quot;&quot;
int add(int a, int b) {
    return a + b;
}
&quot;&quot;&quot;)

print(add(5, 7))  # 12
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;class-support&quot;&gt;Class support&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import py_cpp as pcp

pcp.cpp(r&quot;&quot;&quot;
class Robot {
public:
    int power = 100;
    Robot() {}
    int attack() { return power * 2; }
};
&quot;&quot;&quot;)

r = Robot()
print(r.attack())  # 200
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;public-api&quot;&gt;Public API&lt;/h3&gt;
&lt;p&gt;Only these are intended as public:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;pcp.cpp(code: str) -&amp;gt; module&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;pcp.install(package: str) -&amp;gt; bool&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;pcp.clear_cache() -&amp;gt; None&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;pcp.version() -&amp;gt; str&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;cross-platform-support&quot;&gt;Cross-platform support&lt;/h3&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;OS &lt;/th&gt;&lt;th&gt;Compiler used &lt;/th&gt;&lt;th&gt;Notes&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;Windows &lt;/td&gt;&lt;td&gt;MinGW-w64 &lt;code&gt;g++&lt;/code&gt; (preferred) &lt;/td&gt;&lt;td&gt;Requires &lt;code&gt;g++&lt;/code&gt; on &lt;code&gt;PATH&lt;/code&gt;.&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Linux &lt;/td&gt;&lt;td&gt;&lt;code&gt;g++&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Requires build tools installed.&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;macOS &lt;/td&gt;&lt;td&gt;&lt;code&gt;clang++&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Requires Xcode Command Line Tools.&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Override the compiler via:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;# Windows (PowerShell)
$env:PY_CPP_CXX = &quot;g++&quot;

# Windows (cmd.exe)
set PY_CPP_CXX=g++

# Linux/macOS (bash/zsh)
export PY_CPP_CXX=clang++
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Optional best-effort auto-install (opt-in):&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;# Enable by setting an environment variable in your shell.
# The installer logic is OS-aware (Linux/macOS/Windows) and picks the best available path.

# Windows (PowerShell)
$env:PY_CPP_AUTO_INSTALL_COMPILER = &quot;1&quot;

# Windows (cmd.exe)
set PY_CPP_AUTO_INSTALL_COMPILER=1

# Linux/macOS (bash/zsh)
export PY_CPP_AUTO_INSTALL_COMPILER=1
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;One-shot (only for a single command):&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;# Windows (PowerShell)
$env:PY_CPP_AUTO_INSTALL_COMPILER=&quot;1&quot;; python -c &quot;import py_cpp.toolchain as t; t.ensure_compiler_available(); print('compiler ok')&quot;

# Linux/macOS (bash/zsh)
PY_CPP_AUTO_INSTALL_COMPILER=1 python -c &quot;import py_cpp.toolchain as t; t.ensure_compiler_available(); print('compiler ok')&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note: after an installer runs, you may need to open a new terminal so &lt;code&gt;PATH&lt;/code&gt; updates are visible.&lt;/p&gt;
&lt;h3 id=&quot;vcpkg-package-management&quot;&gt;vcpkg package management&lt;/h3&gt;
&lt;p&gt;Install a C++ library with:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import py_cpp as pcp
pcp.install(&quot;fmt&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If the port does not exist:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;Sorry, library not found.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;py_cpp_pair&lt;/code&gt; detects &lt;code&gt;vcpkg&lt;/code&gt; via &lt;code&gt;VCPKG_ROOT&lt;/code&gt; or &lt;code&gt;PATH&lt;/code&gt;. If missing, it can auto-bootstrap by cloning vcpkg (requires Git).&lt;/p&gt;
&lt;h3 id=&quot;caching-and-build-layout&quot;&gt;Caching and build layout&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;py_cpp_pair&lt;/code&gt; caches builds by SHA256 hash of the C++ source. Reusing identical code reuses the compiled extension.&lt;/p&gt;
&lt;p&gt;Per-user state is stored under &lt;code&gt;PY_CPP_HOME&lt;/code&gt; if set, otherwise the OS-default data directory:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Windows: &lt;code&gt;%LOCALAPPDATA%\\py_cpp&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;macOS: &lt;code&gt;~/Library/Application Support/py_cpp&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Linux: &lt;code&gt;$XDG_DATA_HOME/py_cpp&lt;/code&gt; or &lt;code&gt;~/.local/share/py_cpp&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Subfolders:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;builds/&lt;/code&gt;: compiled extensions per hash&lt;/li&gt;
&lt;li&gt;&lt;code&gt;cache/&lt;/code&gt;: toolchain artifacts (Windows Python import libs)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;logs/&lt;/code&gt;: optional logs (enable with &lt;code&gt;PY_CPP_LOG_FILE=1&lt;/code&gt;)&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;troubleshooting&quot;&gt;Troubleshooting&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;ImportError: DLL load failed (Windows)&lt;/strong&gt;: ensure MinGW runtime DLLs are visible. &lt;code&gt;py_cpp_pair&lt;/code&gt; adds common DLL dirs automatically, but the compiler &lt;code&gt;bin&lt;/code&gt; directory must be on &lt;code&gt;PATH&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;No compiler found&lt;/strong&gt;: install &lt;code&gt;g++&lt;/code&gt;/&lt;code&gt;clang++&lt;/code&gt; and ensure it is on &lt;code&gt;PATH&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;vcpkg bootstrap fails&lt;/strong&gt;: install Git and retry, or set &lt;code&gt;VCPKG_ROOT&lt;/code&gt; to an existing vcpkg checkout.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;performance-notes&quot;&gt;Performance notes&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Compilation is cached by source hash; repeated calls are fast after the first build.&lt;/li&gt;
&lt;li&gt;For larger projects, prefer fewer, bigger &lt;code&gt;cpp()&lt;/code&gt; calls (each call creates a module).&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;documentation&quot;&gt;Documentation&lt;/h3&gt;
&lt;p&gt;See &lt;code&gt;docs/&lt;/code&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;docs/installation.md&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;docs/architecture.md&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;docs/api.md&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;docs/package_manager.md&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;docs/troubleshooting.md&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;docs/examples.md&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;roadmap&quot;&gt;Roadmap&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Better symbol detection (still regex-based by design)&lt;/li&gt;
&lt;li&gt;Multiple translation units / headers&lt;/li&gt;
&lt;li&gt;Better vcpkg library auto-linking&lt;/li&gt;
&lt;li&gt;Optional clang-based parsing for richer bindings&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;contributing&quot;&gt;Contributing&lt;/h3&gt;
&lt;p&gt;See &lt;code&gt;CONTRIBUTING.md&lt;/code&gt;.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/17513/pycpppair</guid>
<pubDate>Tue, 12 May 2026 05:28:32 +0000</pubDate>
</item>
<item>
<title>Building an Expectation-Based AI Governance Model (EBAGM) in Python</title>
<link>https://coderlegion.com/13771/building-an-expectation-based-ai-governance-model-ebagm-in-python</link>
<description>&lt;h2 id=&quot;building-an-expectation-based-ai-governance-model-ebagm-in-python&quot;&gt;Building an Expectation-Based AI Governance Model (EBAGM) in Python&lt;/h2&gt;
&lt;p&gt;&lt;em&gt;What if AI governance wasn’t just about accuracy—but about aligning with human expectations?&lt;/em&gt;&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;introduction&quot;&gt;Introduction&lt;/h3&gt;
&lt;p&gt;Most AI systems today are evaluated using metrics like &lt;strong&gt;accuracy, precision, and recall&lt;/strong&gt;. But in real-world scenarios, that’s not enough.&lt;/p&gt;
&lt;p&gt;A model can be &lt;em&gt;technically correct&lt;/em&gt; and still feel &lt;strong&gt;unfair, biased, or unethical&lt;/strong&gt; to humans.&lt;/p&gt;
&lt;p&gt;This is where a new idea comes in:&lt;/p&gt;
&lt;blockquote&gt;&lt;p&gt;&lt;strong&gt;Expectation-Based AI Governance Model (EBAGM)&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Instead of only focusing on data and outputs, EBAGM introduces:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Human &lt;strong&gt;expectations&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Perceived intent&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;Ethical alignment&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In this blog, I’ll walk you through building a &lt;strong&gt;working prototype in Python&lt;/strong&gt;.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;-what-is-ebagm-&quot;&gt;⚙️ What is EBAGM?&lt;/h3&gt;
&lt;p&gt;EBAGM is a governance framework with 5 layers:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Expectation Layer (E)&lt;/strong&gt; → What humans expect (fairness, privacy, etc.)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Data Governance (D → D')&lt;/strong&gt; → Modify data based on expectations&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Model (M)&lt;/strong&gt; → AI decision-making&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Perceived Intent (P)&lt;/strong&gt; → Does AI &lt;em&gt;feel&lt;/em&gt; fair?&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Feedback Loop&lt;/strong&gt; → Adjust system if misaligned&lt;/li&gt;
&lt;/ol&gt;
&lt;hr&gt;
&lt;h3 id=&quot;step-1-creating-a-biased-dataset&quot;&gt;Step 1: Creating a Biased Dataset&lt;/h3&gt;
&lt;p&gt;We simulate a loan approval system with built-in bias.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import pandas as pd
import numpy as np

np.random.seed(42)

data = pd.DataFrame({
    &quot;income&quot;: np.random.randint(20000, 100000, 100),
    &quot;credit_score&quot;: np.random.randint(300, 850, 100),
    &quot;gender&quot;: np.random.choice([0, 1], 100)
})

data[&quot;approved&quot;] = (
    (data[&quot;income&quot;] &amp;gt; 50000) &amp;amp;
    (data[&quot;credit_score&quot;] &amp;gt; 600)
).astype(int)

# Bias toward males
data.loc[data[&quot;gender&quot;] == 1, &quot;approved&quot;] |= (np.random.rand(100) &amp;gt; 0.7)
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;step-2-defining-expectations&quot;&gt;Step 2: Defining Expectations&lt;/h3&gt;
&lt;p&gt;This is the core of EBAGM.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;expectations = {
    &quot;fairness&quot;: 0.9,
    &quot;accuracy&quot;: 0.8,
    &quot;privacy&quot;: 0.7
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt; Here, fairness is prioritized.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;-step-3-data-governance&quot;&gt;⚖️ Step 3: Data Governance&lt;/h3&gt;
&lt;p&gt;If fairness is high, we remove sensitive attributes.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def apply_governance(data, expectations):
    data = data.copy()
    
    if expectations[&quot;fairness&quot;] &amp;gt; 0.8:
        data = data.drop(columns=[&quot;gender&quot;])
    
    return data

governed_data = apply_governance(data, expectations)
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;step-4-train-the-model&quot;&gt;Step 4: Train the Model&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression

X = governed_data.drop(columns=[&quot;approved&quot;])
y = governed_data[&quot;approved&quot;]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

model = LogisticRegression()
model.fit(X_train, y_train)

predictions = model.predict(X_test)
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;step-5-perceived-intent-score-pis-&quot;&gt;Step 5: Perceived Intent Score (PIS)&lt;/h3&gt;
&lt;p&gt;This is the &lt;strong&gt;key innovation&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Instead of just checking accuracy, we measure:&lt;/p&gt;
&lt;blockquote&gt;&lt;p&gt;Does the model &lt;em&gt;appear fair&lt;/em&gt;?&lt;/p&gt;
&lt;/blockquote&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def perceived_intent_score(original_data, X_test, predictions, expectations):
    df = original_data.loc[X_test.index].copy()
    df[&quot;pred&quot;] = predictions
    
    male_rate = df[df[&quot;gender&quot;] == 1][&quot;pred&quot;].mean()
    female_rate = df[df[&quot;gender&quot;] == 0][&quot;pred&quot;].mean()
    
    bias = abs(male_rate - female_rate)
    
    pis = 1 - (bias * expectations[&quot;fairness&quot;])
    
    return round(pis, 3), round(bias, 3)

pis, bias = perceived_intent_score(data, X_test, predictions, expectations)
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;step-6-governance-feedback&quot;&gt;Step 6: Governance Feedback&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def governance_feedback(pis, threshold=0.75):
    if pis &amp;lt; threshold:
        return &quot;⚠️ Misalignment detected&quot;
    else:
        return &quot;✅ System aligned&quot;

print(governance_feedback(pis))
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;sample-output&quot;&gt;Sample Output&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;Perceived Intent Score (PIS): 0.955
Bias: 0.05

✅ System aligned with expectations
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;key-insight&quot;&gt;Key Insight&lt;/h3&gt;
&lt;p&gt;Even though the model doesn’t explicitly optimize fairness, &lt;strong&gt;governance decisions (like removing gender)&lt;/strong&gt; improved ethical alignment.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;-experiment-lower-fairness&quot;&gt;⚠️ Experiment: Lower Fairness&lt;/h3&gt;
&lt;p&gt;Change:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;&quot;fairness&quot;: 0.2
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Gender is NOT removed&lt;/li&gt;
&lt;li&gt;Bias increases&lt;/li&gt;
&lt;li&gt;PIS drops&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt; You may see:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;⚠️ Misalignment detected
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;why-this-matters&quot;&gt;Why This Matters&lt;/h3&gt;
&lt;p&gt;Traditional AI governance focuses on:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Data quality&lt;/li&gt;
&lt;li&gt;Model performance&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;EBAGM adds something new:&lt;/p&gt;
&lt;blockquote&gt;&lt;p&gt;&lt;strong&gt;Human expectation alignment&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;This leads to three new concepts:&lt;/p&gt;
&lt;h4 id=&quot;1-expectation-misalignment&quot;&gt;1. Expectation Misalignment&lt;/h4&gt;
&lt;p&gt;When AI is correct but feels wrong&lt;/p&gt;
&lt;h4 id=&quot;2-perceived-consciousness-risk&quot;&gt;2. Perceived Consciousness Risk&lt;/h4&gt;
&lt;p&gt;When humans think AI has intent&lt;/p&gt;
&lt;h4 id=&quot;3-utility-vs-ethics-conflict&quot;&gt;3. Utility vs Ethics Conflict&lt;/h4&gt;
&lt;p&gt;When optimization clashes with fairness&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;final-thoughts&quot;&gt;Final Thoughts&lt;/h3&gt;
&lt;p&gt;EBAGM is a simple but powerful idea:&lt;/p&gt;
&lt;blockquote&gt;&lt;p&gt;AI systems shouldn’t just be &lt;em&gt;correct&lt;/em&gt;—they should be &lt;em&gt;aligned with human expectations&lt;/em&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;This prototype shows how we can:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Embed ethics into pipelines&lt;/li&gt;
&lt;li&gt;Quantify perceived fairness&lt;/li&gt;
&lt;li&gt;Build adaptive governance systems&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h3 id=&quot;what-s-next-&quot;&gt;What’s Next?&lt;/h3&gt;
&lt;p&gt;You can extend this by:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Adding fairness metrics (demographic parity, equal opportunity)&lt;/li&gt;
&lt;li&gt;Using real datasets (Kaggle)&lt;/li&gt;
&lt;li&gt;Adding explainability (SHAP, LIME)&lt;/li&gt;
&lt;li&gt;Running multi-scenario experiments&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h3 id=&quot;closing-idea&quot;&gt;Closing Idea&lt;/h3&gt;
&lt;blockquote&gt;&lt;p&gt;“The future of AI governance is not just about controlling systems, but about aligning them with how humans &lt;em&gt;expect them to behave&lt;/em&gt;.”&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;p&gt;If you’re exploring AI ethics, data governance, or philosophy of AI—this is a space worth building in.&lt;/p&gt;
&lt;p&gt;Let me know if you want the &lt;strong&gt;research paper version&lt;/strong&gt; or a &lt;strong&gt;GitHub-ready project&lt;/strong&gt; &lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/13771/building-an-expectation-based-ai-governance-model-ebagm-in-python</guid>
<pubDate>Tue, 31 Mar 2026 12:02:37 +0000</pubDate>
</item>
<item>
<title>Three Ways to Read from a Dict in Python</title>
<link>https://coderlegion.com/10348/three-ways-to-read-from-a-dict-in-python</link>
<description>&lt;p&gt;Reading values from a dictionary looks trivial in Python.&lt;/p&gt;
&lt;p&gt;But depending on how you do it, you may introduce silent bugs, unexpected KeyErrors, or logic errors that only appear in production.&lt;/p&gt;
&lt;p&gt;In this short tutorial, we’ll compare:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Direct indexing&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;dict.get()&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;dict.setdefault()&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;And see when each one is correct — and when it’s dangerous.&lt;/p&gt;
&lt;h3 id=&quot;1-direct-indexing&quot;&gt;1. Direct indexing&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;config = {&quot;timeout&quot;: 10}

timeout = config[&quot;timeout&quot;]      # OK
retries = config[&quot;retries&quot;]      # KeyError
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;when-to-use-it&quot;&gt;When to use it&lt;/h4&gt;
&lt;p&gt;Use direct indexing only when the key must exist.&lt;/p&gt;
&lt;h3 id=&quot;2-dict-get-safe-reads&quot;&gt;2. dict.get(): Safe Reads&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;timeout = config.get(&quot;timeout&quot;, 5)
retries = config.get(&quot;retries&quot;, 3)
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;when-to-use-it-1&quot;&gt;When to use it&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;To avoid KeyErrors, when key doesn't exist&lt;/li&gt;
&lt;li&gt;When key doesn't exist, want to return a default value&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;3-dict-setdefault-read-initialize&quot;&gt;3. dict.setdefault(): Read + Initialize&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;counts = {}

counts.setdefault(&quot;apple&quot;, 0)
counts[&quot;apple&quot;] += 1
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;when-to-use-it-2&quot;&gt;When to use it&lt;/h4&gt;
&lt;p&gt;Whe a key doesn't exist, you want to create it.&lt;/p&gt;
&lt;h3 id=&quot;final-rule-of-thumb&quot;&gt;Final rule of thumb&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Use d[key] when the key must exist&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Use get() when missing keys are normal&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Use setdefault() only when initializing structures&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
</description>
<category>Tutorials</category>
<guid isPermaLink="true">https://coderlegion.com/10348/three-ways-to-read-from-a-dict-in-python</guid>
<pubDate>Fri, 23 Jan 2026 12:08:24 +0000</pubDate>
</item>
<item>
<title>Building a Production-Ready Ecommerce Backend with FastAPI</title>
<link>https://coderlegion.com/9935/building-a-production-ready-ecommerce-backend-with-fastapi</link>
<description>&lt;p&gt;When learning backend development, most projects stop at CRUD APIs.&lt;br&gt;
I wanted to go a step further and build a realistic ecommerce backend—one that follows industry practices, not shortcuts.&lt;/p&gt;
&lt;p&gt;This blog walks through what I built, why I built it that way, and the key backend concepts involved.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Project Goal&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;To design a secure, scalable ecommerce backend that handles:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Authentication&lt;/li&gt;
&lt;li&gt;Cart management&lt;/li&gt;
&lt;li&gt;Checkout flow&lt;/li&gt;
&lt;li&gt;Orders&lt;/li&gt;
&lt;li&gt;Payments&lt;/li&gt;
&lt;li&gt;Stock consistency&lt;/li&gt;
&lt;li&gt;Password recovery&lt;br&gt;
All while following real-world backend design principles.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Tech Stack&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;FastAPI – high-performance Python API framework&lt;/li&gt;
&lt;li&gt;SQLAlchemy – ORM for database modeling&lt;/li&gt;
&lt;li&gt;PostgreSQL – relational database&lt;/li&gt;
&lt;li&gt;Alembic – database migrations&lt;/li&gt;
&lt;li&gt;JWT – authentication&lt;/li&gt;
&lt;li&gt;bcrypt – password hashing&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Authentication &amp;amp; Security&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Passwords are never stored in plain text.&lt;br&gt;
Passwords are hashed using bcrypt&lt;br&gt;
JWT is used for authentication&lt;br&gt;
Password recovery is handled via secure, time-bound reset tokens&lt;br&gt;
No password is ever decrypted or sent back to users&lt;br&gt;
Password recovery is implemented by resetting, not revealing passwords.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Cart Design (Temporary State)&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The cart is designed as a mutable, temporary state:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Users can add, update, or remove items&lt;/li&gt;
&lt;li&gt;Only one active cart per user&lt;/li&gt;
&lt;li&gt;Prices are snapshotted at the time of adding to cart&lt;/li&gt;
&lt;li&gt;This prevents price mismatch issues during checkout.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Checkout (State Transition)&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Checkout is a critical boundary:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Converts a cart into an immutable order&lt;/li&gt;
&lt;li&gt;Validates stock&lt;/li&gt;
&lt;li&gt;Calculates final price&lt;/li&gt;
&lt;li&gt;Creates a PENDING order&lt;/li&gt;
&lt;li&gt;Cart represents intent.&lt;/li&gt;
&lt;li&gt;Checkout represents commitment.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Orders (Immutable Records)&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Orders are treated as financial records:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Created only via checkout &lt;/li&gt;
&lt;li&gt;Read-only for users&lt;/li&gt;
&lt;li&gt;Status-based lifecycle: PENDING → PAID → CANCELLED&lt;/li&gt;
&lt;li&gt;This ensures auditability and consistency.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Payments (Asynchronous &amp;amp; Safe)&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Payments are handled separately from checkout:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Payment intents are created for orders&lt;/li&gt;
&lt;li&gt;Payments are confirmed asynchronously&lt;/li&gt;
&lt;li&gt;Stock is reduced only after payment success&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This avoids overselling and handles real payment gateway behavior.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Stock Management&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Stock updates are protected using row-level locking to avoid race conditions during concurrent purchases.&lt;/p&gt;
&lt;p&gt;Stock is reduced only after confirmed payment—not during checkout.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;API Documentation&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Swagger (OpenAPI) is fully integrated:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Cleanly grouped APIs&lt;/li&gt;
&lt;li&gt;Request &amp;amp; response schemas&lt;/li&gt;
&lt;li&gt;JWT authorization support&lt;/li&gt;
&lt;li&gt;Ready for frontend or third-party integration&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Database Migrations&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;All schema changes are managed via Alembic migrations&lt;/li&gt;
&lt;li&gt;No manual DB edits&lt;/li&gt;
&lt;li&gt;Reproducible environments&lt;/li&gt;
&lt;li&gt;Safe schema evolution&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img src=&quot;https://coderlegion.com/?qa=blob&amp;amp;qa_blobid=6023982787907800547&quot; alt=&quot;&quot;&gt;&lt;br&gt;
&lt;strong&gt;What I Learned&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Why carts and orders must be separate&lt;/li&gt;
&lt;li&gt;Why payments must be asynchronous&lt;/li&gt;
&lt;li&gt;Why passwords must be irreversible&lt;/li&gt;
&lt;li&gt;How ORM relationships fail if not symmetric&lt;/li&gt;
&lt;li&gt;How real-world ecommerce systems prevent overselling&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Source Code&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The complete project is available on GitHub:&lt;br&gt;
 &lt;em&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/sanjay-dot/Ecommerce&quot;&gt;https://github.com/sanjay-dot/Ecommerce&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Final Thoughts&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;This project helped me move from API writing to system thinking.&lt;/p&gt;
&lt;p&gt;If you’re learning backend development, I highly recommend building projects that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;model real workflows&lt;/li&gt;
&lt;li&gt;enforce correct state transitions&lt;/li&gt;
&lt;li&gt;prioritize security from day one&lt;/li&gt;
&lt;/ul&gt;
</description>
<category>Tutorials</category>
<guid isPermaLink="true">https://coderlegion.com/9935/building-a-production-ready-ecommerce-backend-with-fastapi</guid>
<pubDate>Sun, 18 Jan 2026 08:03:04 +0000</pubDate>
</item>
</channel>
</rss>