<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kapil Dagur on Medium]]></title>
        <description><![CDATA[Stories by Kapil Dagur on Medium]]></description>
        <link>https://medium.com/@kapildagur?source=rss-7755415cbdb5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LEfRgVnkg_oXsHQvR1TXIw.jpeg</url>
            <title>Stories by Kapil Dagur on Medium</title>
            <link>https://medium.com/@kapildagur?source=rss-7755415cbdb5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 13:04:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kapildagur/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SSHole: How a crypt() Error Let Disabled Passwords Log In to sshd on musl]]></title>
            <link>https://kapildagur.medium.com/sshole-how-a-crypt-error-let-disabled-passwords-log-in-to-sshd-on-musl-27e41ee387fd?source=rss-7755415cbdb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/27e41ee387fd</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[openssh]]></category>
            <category><![CDATA[openssh-server]]></category>
            <category><![CDATA[sshole]]></category>
            <category><![CDATA[sshd]]></category>
            <dc:creator><![CDATA[Kapil Dagur]]></dc:creator>
            <pubDate>Wed, 11 Nov 2026 07:17:48 GMT</pubDate>
            <atom:updated>2026-11-11T07:17:48.532Z</atom:updated>
            <content:encoded><![CDATA[<h3>An account with no password should never accept one. On some Alpine servers, it did.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7anCzlYnyVwA9TVCGf3PvA.png" /></figure><p>On 5 November 2026, OpenSSH shipped 10.6p2 with exactly one change: a workaround for a password authentication bypass on Linux systems that use musl libc with PAM disabled. Alpine pushed patched packages the same day. It’s tracked as CVE-2026–123158, SAFE Security named it “SSHole” and rated it 8.1 (High), and it was reported by Özgün Kültekin of Wakefield.</p><p>The advisories say “upgrade”, and you should. But I wanted to know <em>why</em> it happened. So I read the code on both sides, sshd and musl, and ran musl’s crypt() myself. The bug turns out to be tiny, easy to follow, and a great lesson for anyone who writes code that returns error values. Let&#39;s dig in.</p><h3>Am I Affected? 🤔</h3><p>All of these have to be true:</p><pre>+--------------------------------------------+-----------------------------+<br>| Condition                                  | How to check                |<br>+--------------------------------------------+-----------------------------+<br>| OpenSSH older than 10.6p2 (or an unfixed   | sshd -V                     |<br>| Alpine package)                            | apk list --installed        |<br>|                                            |   &#39;openssh*&#39;                |<br>| sshd is linked against musl                | ls /lib/ld-musl-*           |<br>| sshd doesn&#39;t use PAM                       | sshd -T | grep -i usepam    |<br>|                                            | (nothing, or &quot;usepam no&quot;)   |<br>| Password authentication is on              | sshd -T | grep -i           |<br>|                                            |   passwordauthentication    |<br>| A login account has &quot;*&quot; as its password    | see &quot;Checking your systems&quot; |<br>| Another account has a $5$ or $6$ hash      | see &quot;Checking your systems&quot; |<br>+--------------------------------------------+-----------------------------+</pre><p>Alpine is the obvious one: musl, and its default openssh-server is built without PAM. Even the openssh-server-pam build defaults to UsePAM no on Alpine 3.22, so it takes the same code path unless you turn PAM on. Debian, Ubuntu and RHEL are not affected, and the reason why is the most interesting part of the story.</p><h3>First, What’s in That Password Field?</h3><pre>+---------------+---------------------------------------------------+<br>| Value         | Meaning                                           |<br>+---------------+---------------------------------------------------+<br>| $6$salt$hash  | SHA-512 hash ($5$ SHA-256, $1$ MD5, $2b$ bcrypt)  |<br>| *             | No password ever set. Nothing can hash to &quot;*&quot;.    |<br>| ! or !hash    | Locked account (passwd -l)                        |<br>| (empty)       | No password; refused unless PermitEmptyPasswords  |<br>+---------------+---------------------------------------------------+</pre><p>That * marker rests on one assumption: no password can ever hash to *. True, as long as crypt() only ever returns real hashes. On musl, it doesn&#39;t.</p><h3>How sshd Checks a Password Without PAM</h3><p>Without PAM, OpenSSH checks passwords itself in sys_auth_passwd(). Here&#39;s the important part, as it was before the fix:</p><pre>/*<br> * Encrypt the candidate password using the proper salt, or pass a<br> * NULL and let xcrypt pick one.<br> */<br>if (authctxt-&gt;valid &amp;&amp; pw_password[0] &amp;&amp; pw_password[1])<br>    salt = pw_password;<br>encrypted_password = xcrypt(password, salt);<br><br>/*<br> * Authentication is accepted if the encrypted passwords<br> * are identical.<br> */<br>return encrypted_password != NULL &amp;&amp;<br>    strcmp(encrypted_password, pw_password) == 0;</pre><p>Classic Unix: hash what the user typed using the stored value as the salt, and accept if the result equals the stored value. Look at the salt line though. A stored * is one character long, so pw_password[1] is the terminating zero and the salt stays NULL.</p><p>With a NULL salt, xcrypt() calls pick_salt(). That exists so sshd spends the same time on accounts without a real hash as on accounts with one, otherwise response times would leak which accounts have passwords. It walks the password database and borrows the prefix of the first hash that starts with $.</p><p>So if alpine has * and root has a $6$ hash, a login as alpine gets hashed as SHA-512 with root&#39;s salt, and the result is compared with *. Nothing wrong yet. It&#39;s only safe as long as crypt() can&#39;t return *.</p><h3>What musl’s crypt() Returns When It Fails 😬</h3><p>musl’s SHA-512 code refuses keys longer than 256 bytes:</p><pre>#define KEY_MAX 256<br><br>/* in sha512crypt(): reject large keys */<br>for (i = 0; i &lt;= KEY_MAX &amp;&amp; key[i]; i++);<br>if (i &gt; KEY_MAX)<br>    return 0;</pre><p>Fair enough: SHA-crypt work grows with key length, so an unbounded key is a cheap way to burn CPU. The problem is what the public wrapper does with that failure:</p><pre>p = sha512crypt(key, setting, output);<br>/* self test and stack cleanup */<br>q = sha512crypt(testkey, testsetting, testbuf);<br>if (!p || q != testbuf || memcmp(testbuf, testhash, sizeof testhash))<br>    return &quot;*&quot;;<br>return p;</pre><p>Any failure returns the string &quot;*&quot;. I checked it on Alpine 3.22.8 with a tiny C program:</p><pre>salt=$6$  len=256  -&gt; $6$$.li6TVmnFwaNje3g...<br>salt=$6$  len=257  -&gt; *<br>salt=$6$  len=1024 -&gt; *<br>salt=$5$  len=257  -&gt; *<br>salt=$1$  len=257  -&gt; $1$$oiNhWHvhmJpyzoQX...<br>salt=xx   len=257  -&gt; xxJJqYuu8A9oE</pre><p>256 bytes: a hash. 257 and up: * for SHA-256 and SHA-512. MD5 and DES keep hashing, which is why the bug needs a $5$ or $6$ hash somewhere on the box for pick_salt() to borrow.</p><h3>Putting It Together</h3><ol><li>A client logs in as an account whose field is *, with a password of 257 to 1024 bytes (sshd caps passwords at 1024).</li><li>The stored value is one character, so no salt is passed and pick_salt() borrows another account&#39;s $6$ prefix.</li><li>musl rejects the long key and returns &quot;*&quot;.</li><li>strcmp(&quot;*&quot;, &quot;*&quot;) is 0. Login accepted.</li></ol><p>No stolen credentials, no keys. Just a shell with whatever rights that account has.</p><blockquote><em>Accounts locked with </em><em>! are safe here: the salt is borrowed the same way, but </em><em>&quot;*&quot; doesn&#39;t equal </em><em>&quot;!&quot;.</em></blockquote><h3>Why glibc Systems Are Fine</h3><p>Most glibc distros get crypt() from libxcrypt. Same check on Debian 13:</p><pre>$6$  256  -&gt; $6$$.li6TVmnFwaNje3g...<br>$6$  257  -&gt; $6$$VVoAsM9yOuDXnTJT...<br>$6$  512  -&gt; *0<br>$6$  1024 -&gt; *0<br>setting &quot;*0&quot;  -&gt; *1</pre><p>libxcrypt accepts longer keys (up to 511 bytes), but the real difference is the failure value: *0, or *1 if the setting itself starts with *0. Its man page says the invalid hash &quot;will not compare equal to setting&quot;, and that this is &quot;chosen to make these applications fail closed when an error occurs&quot;. It&#39;s also two characters, so it can never match a one-character *. musl&#39;s failure value is exactly that one character, the most common marker for &quot;no password&quot;.</p><p>The whole bug in one sentence: <strong>the error value of one library was a valid value in the data another program compared it against.</strong></p><h3>The Fix in OpenSSH 10.6p2 🔧</h3><p>Damien Miller’s commit is short. The part that closes the hole:</p><pre>+#define MIN_PASSWORD_HASH_LEN    4<br>...<br>-    return encrypted_password != NULL &amp;&amp;<br>+    ret = encrypted_password != NULL &amp;&amp;<br>+        strlen(pw_password) &gt;= MIN_PASSWORD_HASH_LEN &amp;&amp;<br>         strcmp(encrypted_password, pw_password) == 0;</pre><p>No real hash is shorter than four characters (even old DES is 13), so *, ! or !! can never match again, whatever crypt() returns. The rest of the commit makes sure the stored hash is copied and wiped with freezero() after use.</p><p>The release notes put it plainly: “We consider the root cause of this bug to be outside sshd, but it is exploitable via sshd and can be avoided there.” Fair. sshd makes the security decision, so the check belongs there, and it can’t assume every libc fails the way glibc does.</p><h3>The Alpine Cloud Image Twist</h3><p>SAFE Security points out that official Alpine cloud images from 3.18.11 to 3.24.3 create an alpine account with * and passwordless doas. A fresh image isn&#39;t exploitable, since there&#39;s no $5$/$6$ hash to borrow. But set a password on any account (say, a root password for the serial console) with password auth on, and a login as alpine leads straight to root. Two harmless-looking settings, one serious hole.</p><h3>Checking Your Systems 🔍</h3><pre>sshd -V<br>ls /lib/ld-musl-* 2&gt;/dev/null &amp;&amp; echo &quot;musl&quot;<br>sshd -T | grep -Ei &#39;^(usepam|passwordauthentication|permitrootlogin) &#39;<br><br># Accounts with &quot;*&quot; and a shell that is not nologin or false<br>awk -F: &#39;NR==FNR { if ($2 == &quot;*&quot;) star[$1]; next }<br>         ($1 in star) &amp;&amp; $7 !~ /(nologin|false)$/ { print $1, $7 }&#39; \<br>    /etc/shadow /etc/passwd<br><br># Number of SHA-256 or SHA-512 hashes on the system<br>awk -F: &#39;$2 ~ /^\$[56]\$/&#39; /etc/shadow | wc -l</pre><p>An account in the first list, a number above zero in the second, sshd older than 10.6p2 and password auth on? That host is exposed.</p><p>Heads-up: expect root in that list. In the Alpine 3.22 container image, root&#39;s field is *. The default PermitRootLogin without-password protects it, but if someone changed that to yes, root itself is the way in. Users made with adduser -D get ! and are fine.</p><p>For past use, look for password logins to those accounts (Alpine logs to /var/log/messages):</p><pre>grep &#39;Accepted password for&#39; /var/log/messages</pre><p>sshd doesn’t log password length, so the signal is simply a successful password login to an account that has no password.</p><h3>What to Do</h3><p><strong>Upgrade, then restart sshd.</strong> Alpine’s fixed openssh versions:</p><pre>+--------+-------------------------+<br>| Branch | Fixed version           |<br>+--------+-------------------------+<br>| edge   | 10.6_p2-r0              |<br>| 3.24   | 10.3_p1-r2              |<br>| 3.23   | 10.2_p1-r1              |<br>| 3.22   | 10.0_p1-r11             |<br>| 3.21   | 9.9_p2-r1               |<br>| 3.20   | 9.7_p1-r6               |<br>| 3.19   | 9.7_p2-r5 or 9.6_p1-r3  |<br>+--------+-------------------------+</pre><pre>apk update &amp;&amp; apk upgrade<br>rc-service sshd restart</pre><p>Don’t skip the restart: the running sshd keeps the old code until it restarts. For containers, rebuild and redeploy.</p><p><strong>Can’t upgrade today? Turn off password auth.</strong> Confirm key login works in a second session first, then set PasswordAuthentication no (check your Match blocks too), run sshd -t, and restart.</p><p><strong>Then shrink the blast radius:</strong> review passwordless sudo/doas, and keep SSH behind a VPN or bastion where you can.</p><h3>What I Take Away as a Developer 💡</h3><p>I write Python services, not SSH daemons, but this pattern is everywhere: a function signals failure with a value that’s also a valid result. A -1 that&#39;s also a valid index. An empty string that&#39;s also a valid name. A &quot;*&quot; that&#39;s also a password marker.</p><ul><li><strong>Make errors impossible to confuse with data.</strong> Raise, return None, or use a result type. If you must use a sentinel, pick one that can never equal a valid value, like libxcrypt does.</li><li><strong>Validate the shape before comparing.</strong> That’s literally what the OpenSSH fix does.</li><li><strong>Read the failure contract of your dependencies.</strong> Same function name, different libc, different failure. Correct on glibc, wrong on musl.</li><li><strong>Test just past every limit.</strong> One 257-byte password on a musl build would have caught this.</li></ul><h3>Where to Go Next</h3><ul><li>📖 <a href="https://www.openssh.org/releasenotes.html">OpenSSH 10.6p2 release notes</a></li><li>💻 <a href="https://github.com/openssh/openssh-portable/commit/4353fdc43ef646c43a8dda7025cc1a898caf1482">The fix commit</a> and <a href="https://git.musl-libc.org/cgit/musl/tree/src/crypt/crypt_sha512.c">musl’s crypt_sha512.c</a></li><li>🛡️ <a href="https://security.alpinelinux.org/vuln/CVE-2026-123158">Alpine security tracker: CVE-2026–123158</a></li><li>📰 <a href="https://safe.security/resources/blog/sshole-high-severity-openssh-vulnerability-turns-disabled-passwords-into-unauthorized-access/">SAFE Security’s SSHole write-up</a></li><li>📚 <a href="https://github.com/besser82/libxcrypt/blob/develop/doc/crypt.3">libxcrypt crypt(3)</a></li></ul><h3>Final Thought</h3><p>Nothing exotic here: no memory corruption, no race, no broken crypto. Two pieces of code, each reasonable on its own, disagreed about what &quot;*&quot; means. Those are the bugs I find most worth reading about, because they&#39;re the ones I could write myself.</p><p>Run Alpine anywhere? Check today: upgrade, restart sshd, and turn off password auth where you don’t need it.</p><p><em>Last updated November 2026, OpenSSH 10.6p2. Also on </em><a href="https://kapildagur.github.io/blog/sshole-musl-crypt/"><em>my blog</em></a><em>. Got questions or feedback? Drop them in the comments!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27e41ee387fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dev Containers(devcontainers) — Your Entire Dev Environment in a Single JSON File]]></title>
            <link>https://kapildagur.medium.com/dev-containers-devcontainers-your-entire-dev-environment-in-a-single-json-file-ec2a982e2f9f?source=rss-7755415cbdb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec2a982e2f9f</guid>
            <category><![CDATA[devcontainer]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[vscode-extension]]></category>
            <dc:creator><![CDATA[Kapil Dagur]]></dc:creator>
            <pubDate>Wed, 15 Apr 2026 07:54:47 GMT</pubDate>
            <atom:updated>2026-04-15T07:54:47.231Z</atom:updated>
            <content:encoded><![CDATA[<p><em>No more “works on my machine.” No more two-hour onboarding. Just one config file, one container, and every developer on your team in the exact same environment.</em> 🐳</p><p>You know that feeling when a new teammate joins, they spend their first day wrestling with environment setup — wrong Python version, missing system libraries, conflicting Node versions — and by the end of the day they’ve written zero code?</p><p>Or maybe this one: you fix a bug locally, push it, and CI fails because the build server has a slightly different version of some dependency. You spend an hour figuring out it’s a gcc version mismatch. Nothing you wrote was wrong.</p><p>Both of these problems have the same root cause: your development environment lives in your head (and your laptop), not in your repository.</p><p><strong>Dev Containers</strong> fix this. They’re a spec, an ecosystem, and a workflow that packages your entire development environment — tools, runtimes, extensions, settings — into a single devcontainer.json file that lives alongside your code. Anyone with Docker and VS Code (or GitHub Codespaces, or any supporting tool) gets the exact same environment with zero manual setup.</p><p>Let’s go through every layer of how this works.</p><h3>What Is a Dev Container, Exactly?</h3><p>Straight from the <a href="https://containers.dev/">official spec</a>:</p><blockquote>“A development container is a container in which a user can develop an application. Development containers provide a complete, consistent coding environment that includes the tools, libraries, runtimes, and configuration needed for working with a specific codebase.”</blockquote><p>The key word is <strong>complete</strong>. Not just a Docker image with your language runtime. The container includes your editor extensions, your linter config, your database sidecar, your environment variables, your post-setup scripts — everything. It’s a reproducible snapshot of your entire development setup.</p><h3>The Architecture Overview 🏗️</h3><p>Before we touch any config, it’s worth understanding how the pieces fit together. This is the mental model you’ll use for everything that follows.</p><pre>┌─────────────────────────────────────────────────────────┐<br>│                    Your Machine (Host)                  │<br>│                                                         │<br>│  ┌─────────────────────────────────────────────────┐    │<br>│  │              Docker / Container Runtime         │    │<br>│  │                                                 │    │<br>│  │  ┌────────────────────────────────────────────┐ │    │<br>│  │  │           Dev Container                    │ │    │<br>│  │  │                                            │ │    │<br>│  │  │  ┌──────────────┐  ┌──────────────────┐    │ │    │<br>│  │  │  │  Base Image  │  │    Features      │    │ │    │<br>│  │  │  │ (Ubuntu,     │  │ (Python, Node,   │    │ │    │<br>│  │  │  │  Debian...)  │  │  Docker, git...) │    │ │    │<br>│  │  │  └──────────────┘  └──────────────────┘    │ │    │<br>│  │  │                                            │ │    │<br>│  │  │  ┌──────────────────────────────────────┐  │ │    │<br>│  │  │  │  Your Source Code (bind mounted)     │  │ │    │<br>│  │  │  └──────────────────────────────────────┘  │ │    │<br>│  │  │                                            │ │    │<br>│  │  │  ┌──────────────────────────────────────┐  │ │    │<br>│  │  │  │  Lifecycle Scripts                   │  │ │    │<br>│  │  │  │  (postCreate, postStart, ...)        │  │ │    │<br>│  │  │  └──────────────────────────────────────┘  │ │    │<br>│  │  └────────────────────────────────────────────┘ │    │<br>│  │                                                 │    │<br>│  │  ┌────────────────┐  ┌────────────────────────┐ │    │<br>│  │  │ Sidecar DB     │  │ Sidecar Redis          │ │    │<br>│  │  │ (postgres...)  │  │ (if Docker Compose)    │ │    │<br>│  │  └────────────────┘  └────────────────────────┘ │    │<br>│  └─────────────────────────────────────────────────┘    │<br>│                                                         │<br>│  ┌───────────────────────────────────────────────────┐  │<br>│  │  Supporting Tool (VS Code / Cursor / Codespaces)  │  │<br>│  │  Reads .devcontainer/devcontainer.json            │  │<br>│  │  Installs extensions inside container             │  │<br>│  └───────────────────────────────────────────────────┘  │<br>└─────────────────────────────────────────────────────────┘</pre><p>Three key points from this architecture:</p><ol><li><strong>Your source code stays on the host</strong> — it’s bind-mounted into the container, so edits are instant and you never lose work if the container is rebuilt.</li><li><strong>Tools run inside the container</strong> — Python, Node, compilers, linters, databases. Nothing pollutes your host machine.</li><li><strong>The editor runs on the host, connects to the container</strong> — VS Code runs locally but executes code, terminals, extensions, and LSP inside the container.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*ZWVxreGPIky3gEZmfNIYsg.png" /><figcaption>architecture-containers</figcaption></figure><h3>The .devcontainer Folder</h3><p>The entire configuration lives in your repository:</p><pre>your-project/<br>├── .devcontainer/<br>│   ├── devcontainer.json    # the main config file<br>│   ├── Dockerfile           # optional, for custom images<br>│   └── docker-compose.yml   # optional, for multi-container setups<br>├── src/<br>│   └── main.py<br>└── README.md</pre><p>Tools implementing the spec look for devcontainer.json in these locations (in order of precedence):</p><ol><li>.devcontainer/devcontainer.json</li><li>.devcontainer.json (root level)</li><li>.devcontainer/&lt;subfolder&gt;/devcontainer.json (for multiple configs)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RCYssHhHboIhQ6DQK8dA4w.png" /><figcaption>Python Inside devcontainer</figcaption></figure><h3>The Three Configuration Approaches</h3><p>The spec supports three ways to define your container — from simplest to most powerful.</p><h3>Approach 1: Image-Based (Simplest)</h3><p>Just reference a prebuilt image. No Dockerfile needed.</p><pre>// .devcontainer/devcontainer.json<br>{<br>  &quot;name&quot;: &quot;Python 3.12&quot;,<br>  &quot;image&quot;: &quot;mcr.microsoft.com/devcontainers/python:3.12&quot;<br>}</pre><p>Microsoft maintains a full set of official dev container base images at mcr.microsoft.com/devcontainers/. There&#39;s one for Python, Node, Go, Java, Rust, .NET, and more — all with common development tools pre-installed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9b21Xg5Q8bxUVUWxnNeSaQ.png" /><figcaption>DevContainer Images</figcaption></figure><h3>Approach 2: Dockerfile-Based (Custom Image)</h3><p>When you need to install system packages or tools that aren’t in a base image:</p><pre>// .devcontainer/devcontainer.json<br>{<br>  &quot;name&quot;: &quot;My Python App&quot;,<br>  &quot;build&quot;: {<br>    &quot;dockerfile&quot;: &quot;Dockerfile&quot;,<br>    &quot;args&quot;: {<br>      &quot;PYTHON_VERSION&quot;: &quot;3.12&quot;<br>    }<br>  },<br>  &quot;forwardPorts&quot;: [8000]<br>}</pre><pre># .devcontainer/Dockerfile<br>ARG PYTHON_VERSION=3.12<br>FROM mcr.microsoft.com/devcontainers/python:${PYTHON_VERSION}<br><br># Install any system-level dependencies<br>RUN apt-get update &amp;&amp; apt-get install -y \<br>    postgresql-client \<br>    redis-tools \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*</pre><p>The Dockerfile runs during the image build phase — before the container starts. It’s best for system-level dependencies. For project-level setup (like pip install), use lifecycle scripts instead.</p><h3>Approach 3: Docker Compose (Multi-Container)</h3><p>For projects that need a database, cache, or other services alongside your main container:</p><pre>// .devcontainer/devcontainer.json<br>{<br>  &quot;name&quot;: &quot;Django + Postgres&quot;,<br>  &quot;dockerComposeFile&quot;: &quot;docker-compose.yml&quot;,<br>  &quot;service&quot;: &quot;app&quot;,<br>  &quot;workspaceFolder&quot;: &quot;/workspace&quot;<br>}</pre><pre># .devcontainer/docker-compose.yml<br>version: &quot;3.8&quot;<br><br>services:<br>  app:<br>    build:<br>      context: ..<br>      dockerfile: .devcontainer/Dockerfile<br>    volumes:<br>      - ..:/workspace:cached<br>    command: sleep infinity   # keep container running<br>  db:<br>    image: postgres:16<br>    environment:<br>      POSTGRES_PASSWORD: devpassword<br>      POSTGRES_DB: myapp<br>    volumes:<br>      - postgres-data:/var/lib/postgresql/data<br>  redis:<br>    image: redis:7-alpine<br><br>volumes:<br>  postgres-data:</pre><p>Your app container, database, and cache all start together. Ports are accessible from your main dev container. This is the pattern most backend projects end up using.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b1tGKwbMBLPmsLe-GLdyug.png" /><figcaption>DevContainer OverView</figcaption></figure><h3>Features: Modular Tooling 🧩</h3><p>This is one of the most powerful parts of dev containers. <strong>Features</strong> are self-contained, shareable units of installation code that add tooling to any base image — like npm packages but for your dev environment.</p><pre>{<br>  &quot;name&quot;: &quot;Full-Stack Dev&quot;,<br>  &quot;image&quot;: &quot;mcr.microsoft.com/devcontainers/base:ubuntu&quot;,<br>  &quot;features&quot;: {<br>    &quot;ghcr.io/devcontainers/features/python:1&quot;: {<br>      &quot;version&quot;: &quot;3.12&quot;<br>    },<br>    &quot;ghcr.io/devcontainers/features/node:1&quot;: {<br>      &quot;version&quot;: &quot;lts&quot;<br>    },<br>    &quot;ghcr.io/devcontainers/features/docker-in-docker:2&quot;: {<br>      &quot;version&quot;: &quot;latest&quot;,<br>      &quot;moby&quot;: true<br>    },<br>    &quot;ghcr.io/devcontainers/features/git:1&quot;: {},<br>    &quot;ghcr.io/devcontainers/features/github-cli:1&quot;: {}<br>  }<br>}</pre><p>Each Feature is:</p><ul><li><strong>Self-contained</strong> — it’s a folder with a devcontainer-feature.json metadata file and an install.sh script</li><li><strong>OCI-distributed</strong> — pulled from a container registry (GitHub Container Registry, Docker Hub, etc.)</li><li><strong>Versioned</strong> — pin to a major version (:1) or exact version (:1.2.3)</li><li><strong>Composable</strong> — add as many as you need; they’re installed in sequence (or parallel where specified)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d1Dbi8kzGvVWhQ_Qchc6vw.png" /><figcaption>DevContainers Features</figcaption></figure><h3>How Features Work Internally</h3><p>Each Feature has this structure:</p><pre>my-feature/<br>├── devcontainer-feature.json    ← metadata (name, version, options)<br>└── install.sh                   ← the actual installation script</pre><pre>// devcontainer-feature.json<br>{<br>  &quot;id&quot;: &quot;python&quot;,<br>  &quot;version&quot;: &quot;1.2.3&quot;,<br>  &quot;name&quot;: &quot;Python&quot;,<br>  &quot;options&quot;: {<br>    &quot;version&quot;: {<br>      &quot;type&quot;: &quot;string&quot;,<br>      &quot;default&quot;: &quot;os-provided&quot;,<br>      &quot;description&quot;: &quot;Python version to install&quot;<br>    }<br>  }<br>}</pre><p>When you add a Feature to devcontainer.json, the tool downloads it from the OCI registry, runs install.sh as root inside the container during the image build step, and the tool is available for the rest of the container&#39;s life.</p><h3>The Lifecycle — What Runs When 🔄</h3><p>This is the section most people find confusing, so let’s be thorough. The official spec defines five lifecycle commands that run at specific points:</p><pre>HOST MACHINE                    CONTAINER<br>─────────────────────────────────────────────────────────────<br>initializeCommand      ←     Runs on HOST before container exists<br>                              (e.g., clone a repo, check prerequisites)<br>                              Container is created + image built<br>                              Features are installed<br><br>onCreateCommand        ←     Runs ONCE when container is first created<br>                              (no access to user secrets yet)<br><br>updateContentCommand   ←     Runs ONCE on create; also re-runs when<br>                              cloud service refreshes prebuilt containers<br>                              (e.g., dependency installation for caching)<br><br>postCreateCommand      ←     Runs ONCE after container is assigned to a user<br>                              ✅ Has access to user secrets<br>                              ✅ Has local file access<br>                              (e.g., pip install, npm install, DB migrations)<br>                              Container is now ready<br><br>postStartCommand       ←     Runs EVERY TIME the container starts<br>                              (e.g., start a dev server, run a test watcher)<br><br>postAttachCommand      ←     Runs EVERY TIME a tool attaches<br>                              (e.g., print a welcome message, show status)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6zgXHib-He50E3-XpPlC3w.png" /><figcaption>Merge Logic (devcontainers Properties Guide)</figcaption></figure><h3>Practical Guide: What Goes Where</h3><p>Task Best lifecycle hook Why Check Docker is running initializeCommand Runs on host before container Install system packages Dockerfile or Features Cached in image layer pip install -r requirements.txt postCreateCommand Needs workspace files npm install postCreateCommand Needs workspace files Database migrations postCreateCommand One-time setup Start dev server postStartCommand Needs to restart with container Print welcome message postAttachCommand Every session Start background workers postStartCommand Every container start</p><h3>Parallel Execution (Object Syntax)</h3><p>All lifecycle scripts support running commands in parallel using the object syntax:</p><pre>{<br>  &quot;postCreateCommand&quot;: {<br>    &quot;install-python-deps&quot;: &quot;pip install -r requirements.txt&quot;,<br>    &quot;install-node-deps&quot;: &quot;npm install&quot;,<br>    &quot;setup-db&quot;: &quot;python manage.py migrate&quot;<br>  }<br>}</pre><p>The three commands above run in <strong>parallel</strong>. Each must succeed for the stage to be considered successful. For sequential execution, use a shell script or &amp;&amp;.</p><h3>devcontainer.json — The Full Reference</h3><p>Let’s walk through all the important properties with real examples.</p><h3>Core Identity</h3><pre>{<br>  // Human-readable name (shown in status bar)<br>  &quot;name&quot;: &quot;My Python API&quot;,<br><br>  // What image to base the container on<br>  &quot;image&quot;: &quot;mcr.microsoft.com/devcontainers/python:3.12&quot;,<br><br>  // OR use a Dockerfile<br>  &quot;build&quot;: {<br>    &quot;dockerfile&quot;: &quot;Dockerfile&quot;,<br>    &quot;context&quot;: &quot;..&quot;,<br>    &quot;args&quot;: { &quot;VARIANT&quot;: &quot;3.12-bullseye&quot; }<br>  },<br><br>  // OR use Docker Compose<br>  &quot;dockerComposeFile&quot;: &quot;docker-compose.yml&quot;,<br>  &quot;service&quot;: &quot;app&quot;,<br>}</pre><h3>Ports and Networking</h3><pre>{<br>  // Forward these container ports to the host<br>  &quot;forwardPorts&quot;: [8000, 5432, 6379],<br><br>  // Detailed port configuration<br>  &quot;portsAttributes&quot;: {<br>    &quot;8000&quot;: {<br>      &quot;label&quot;: &quot;Application&quot;,<br>      &quot;onAutoForward&quot;: &quot;notify&quot;   // notify | openBrowser | silent<br>    },<br>    &quot;5432&quot;: {<br>      &quot;label&quot;: &quot;PostgreSQL&quot;,<br>      &quot;onAutoForward&quot;: &quot;silent&quot;<br>    }<br>  }<br>}</pre><h3>Environment Variables</h3><pre>{<br>  // Container env vars (set at container creation)<br>  &quot;containerEnv&quot;: {<br>    &quot;PYTHONPATH&quot;: &quot;/workspace/src&quot;,<br>    &quot;DATABASE_URL&quot;: &quot;postgresql://localhost/devdb&quot;<br>  },<br><br>  // Remote env vars (set when tool attaches)<br>  // Can reference local env vars from your host<br>  &quot;remoteEnv&quot;: {<br>    &quot;LOCAL_WORKSPACE_FOLDER&quot;: &quot;${localWorkspaceFolder}&quot;,<br>    &quot;API_KEY&quot;: &quot;${localEnv:MY_API_KEY}&quot;<br>  }<br>}</pre><h3>Mounts and Volumes</h3><pre>{<br>  &quot;mounts&quot;: [<br>    // Persist your shell history across container rebuilds<br>    {<br>      &quot;source&quot;: &quot;devcontainer-bashhistory&quot;,<br>      &quot;target&quot;: &quot;/commandhistory&quot;,<br>      &quot;type&quot;: &quot;volume&quot;<br>    },<br>    // Mount a local directory<br>    {<br>      &quot;source&quot;: &quot;${localWorkspaceFolder}/data&quot;,<br>      &quot;target&quot;: &quot;/workspace/data&quot;,<br>      &quot;type&quot;: &quot;bind&quot;<br>    }<br>  ]<br>}</pre><h3>User Configuration</h3><pre>{<br>  // User inside the container (avoid running as root)<br>  &quot;remoteUser&quot;: &quot;vscode&quot;,<br>  &quot;containerUser&quot;: &quot;vscode&quot;,<br><br>  // Override the workspace folder inside the container<br>  &quot;workspaceFolder&quot;: &quot;/workspace&quot;,<br>  &quot;workspaceMount&quot;: &quot;source=${localWorkspaceFolder},target=/workspace,type=bind,consistency=cached&quot;<br>}</pre><h3>Lifecycle Scripts</h3><pre>{<br>  &quot;initializeCommand&quot;: &quot;echo &#39;Checking prerequisites on host...&#39;&quot;,<br><br>  &quot;onCreateCommand&quot;: &quot;echo &#39;Container created&#39;&quot;,<br><br>  &quot;updateContentCommand&quot;: &quot;pip install -r requirements.txt&quot;,<br><br>  &quot;postCreateCommand&quot;: {<br>    &quot;python-deps&quot;: &quot;pip install -r requirements.txt&quot;,<br>    &quot;pre-commit&quot;: &quot;pre-commit install&quot;,<br>    &quot;migrate&quot;: &quot;python manage.py migrate --run-syncdb&quot;<br>  },<br><br>  &quot;postStartCommand&quot;: &quot;python manage.py runserver 0.0.0.0:8000 &amp;&quot;,<br><br>  &quot;postAttachCommand&quot;: &quot;echo &#39;\\n🚀 Dev container ready! Run: python manage.py runserver&#39;&quot;<br>}</pre><h3>Editor Customizations</h3><pre>{<br>  &quot;customizations&quot;: {<br>    &quot;vscode&quot;: {<br>      // Extensions installed inside the container<br>      &quot;extensions&quot;: [<br>        &quot;ms-python.python&quot;,<br>        &quot;ms-python.vscode-pylance&quot;,<br>        &quot;charliermarsh.ruff&quot;,<br>        &quot;ms-python.mypy-type-checker&quot;,<br>        &quot;mtxr.sqltools&quot;,<br>        &quot;mtxr.sqltools-driver-pg&quot;<br>      ],<br>      // Settings applied inside the container<br>      &quot;settings&quot;: {<br>        &quot;python.defaultInterpreterPath&quot;: &quot;/usr/local/bin/python&quot;,<br>        &quot;editor.formatOnSave&quot;: true,<br>        &quot;[python]&quot;: {<br>          &quot;editor.defaultFormatter&quot;: &quot;charliermarsh.ruff&quot;,<br>          &quot;editor.codeActionsOnSave&quot;: {<br>            &quot;source.fixAll.ruff&quot;: &quot;explicit&quot;,<br>            &quot;source.organizeImports.ruff&quot;: &quot;explicit&quot;<br>          }<br>        },<br>        &quot;mypy-type-checker.importStrategy&quot;: &quot;fromEnvironment&quot;<br>      }<br>    }<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ODTNKkyO97QhOsFiJYbKZw.png" /><figcaption>VS Code Extensions (Local vs DevContainers)</figcaption></figure><h3>A Complete Real-World Example: FastAPI + PostgreSQL + Redis</h3><p>Let’s put it all together for a realistic Python API project:</p><pre>my-fastapi-project/<br>├── .devcontainer/<br>│   ├── devcontainer.json<br>│   └── docker-compose.yml<br>├── src/<br>│   └── main.py<br>├── requirements.txt<br>└── pyproject.toml</pre><pre>// .devcontainer/devcontainer.json<br>{<br>  &quot;name&quot;: &quot;FastAPI Dev&quot;,<br>  &quot;dockerComposeFile&quot;: &quot;docker-compose.yml&quot;,<br>  &quot;service&quot;: &quot;app&quot;,<br>  &quot;workspaceFolder&quot;: &quot;/workspace&quot;,<br>  &quot;features&quot;: {<br>    &quot;ghcr.io/devcontainers/features/git:1&quot;: {},<br>    &quot;ghcr.io/devcontainers/features/github-cli:1&quot;: {}<br>  },<br>  &quot;forwardPorts&quot;: [8000, 5432, 6379],<br><br>  &quot;portsAttributes&quot;: {<br>    &quot;8000&quot;: { &quot;label&quot;: &quot;FastAPI&quot;, &quot;onAutoForward&quot;: &quot;notify&quot; },<br>    &quot;5432&quot;: { &quot;label&quot;: &quot;PostgreSQL&quot;, &quot;onAutoForward&quot;: &quot;silent&quot; },<br>    &quot;6379&quot;: { &quot;label&quot;: &quot;Redis&quot;, &quot;onAutoForward&quot;: &quot;silent&quot; }<br>  },<br><br>  &quot;postCreateCommand&quot;: {<br>    &quot;install-deps&quot;: &quot;pip install -r requirements.txt&quot;,<br>    &quot;pre-commit&quot;: &quot;pre-commit install&quot;,<br>    &quot;migrate&quot;: &quot;alembic upgrade head&quot;<br>  },<br><br>  &quot;remoteUser&quot;: &quot;vscode&quot;,<br><br>  &quot;customizations&quot;: {<br>    &quot;vscode&quot;: {<br>      &quot;extensions&quot;: [<br>        &quot;ms-python.python&quot;,<br>        &quot;ms-python.vscode-pylance&quot;,<br>        &quot;charliermarsh.ruff&quot;,<br>        &quot;ms-python.mypy-type-checker&quot;,<br>        &quot;mtxr.sqltools&quot;,<br>        &quot;mtxr.sqltools-driver-pg&quot;,<br>        &quot;ms-azuretools.vscode-docker&quot;<br>      ],<br>      &quot;settings&quot;: {<br>        &quot;python.defaultInterpreterPath&quot;: &quot;/usr/local/bin/python&quot;,<br>        &quot;editor.formatOnSave&quot;: true,<br>        &quot;[python]&quot;: {<br>          &quot;editor.defaultFormatter&quot;: &quot;charliermarsh.ruff&quot;<br>        }<br>      }<br>    }<br>  }<br>}</pre><pre># .devcontainer/docker-compose.yml<br>version: &quot;3.8&quot;<br><br>services:<br>  app:<br>    image: mcr.microsoft.com/devcontainers/python:3.12<br>    volumes:<br>      - ..:/workspace:cached<br>    command: sleep infinity<br>    environment:<br>      DATABASE_URL: postgresql://postgres:devpassword@db:5432/myapp<br>      REDIS_URL: redis://redis:6379<br>    depends_on:<br>      - db<br>      - redis<br>  db:<br>    image: postgres:16-alpine<br>    restart: unless-stopped<br>    environment:<br>      POSTGRES_USER: postgres<br>      POSTGRES_PASSWORD: devpassword<br>      POSTGRES_DB: myapp<br>    volumes:<br>      - postgres-data:/var/lib/postgresql/data<br>  redis:<br>    image: redis:7-alpine<br>    restart: unless-stopped<br><br>volumes:<br>  postgres-data:</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NLtdRyDt0HAdst8l2r00Gw.png" /><figcaption>ReOpen in Container</figcaption></figure><p>When a new teammate clones this repo and opens it in VS Code:</p><ol><li>VS Code detects .devcontainer/devcontainer.json and shows &quot;Reopen in Container&quot;</li><li>Docker pulls the Python image and starts Postgres + Redis</li><li>postCreateCommand installs dependencies and runs migrations</li><li>VS Code installs all extensions inside the container</li><li>They have a fully working development environment — in about 2 minutes</li></ol><h3>The Dev Container CLI</h3><p>The <a href="https://github.com/devcontainers/cli">Dev Container CLI</a> is the reference implementation of the spec. It powers VS Code’s Dev Containers extension and GitHub Codespaces under the hood.</p><pre>npm install -g @devcontainers/cli<br><br># Build the dev container image<br>devcontainer build --workspace-folder .<br><br># Start the dev container<br>devcontainer up --workspace-folder .<br><br># Run a command inside the container<br>devcontainer exec --workspace-folder . python --version<br><br># Pre-build and push an image (for faster first-open times)<br>devcontainer build \<br>  --workspace-folder . \<br>  --push \<br>  --image-name ghcr.io/your-org/your-repo-devcontainer:latest</pre><p>The CLI is especially useful in CI/CD — you can use the same dev container definition to run your tests in GitHub Actions:</p><pre># .github/workflows/test.yml<br>name: Test<br>on: [push, pull_request]<br><br>jobs:<br>  test:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br>      - name: Run tests in dev container<br>        uses: devcontainers/ci@v0.3<br>        with:<br>          runCmd: pytest tests/ -v --cov</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ByZHSRY0Cwsj1ofBo5tqgw.png" /><figcaption>Dev Containers CI/CD Support</figcaption></figure><p>devcontainer.json supports several built-in variables that let you write portable configs:</p><p>Variable Value</p><p>${localWorkspaceFolder} Path to project folder on the <strong>host</strong> ${containerWorkspaceFolder} Path to project folder in the <strong>container</strong> ${localWorkspaceFolderBasename} Just the folder name ${localEnv:ENV_VAR_NAME} Value of a host environment variable ${devcontainerId} Unique ID for this dev container</p><pre>{<br>  &quot;mounts&quot;: [<br>    &quot;source=${localWorkspaceFolder}/.cache,target=/root/.cache,type=bind&quot;<br>  ],<br>  &quot;remoteEnv&quot;: {<br>    &quot;AWS_ACCESS_KEY_ID&quot;: &quot;${localEnv:AWS_ACCESS_KEY_ID}&quot;,<br>    &quot;AWS_SECRET_ACCESS_KEY&quot;: &quot;${localEnv:AWS_SECRET_ACCESS_KEY}&quot;<br>  }<br>}</pre><p>This is how you pass secrets from your host machine into the container without hardcoding them.</p><h3>Image Metadata Labels</h3><p>Features and base images can embed devcontainer.json metadata directly into the Docker image using a label:</p><pre>LABEL devcontainer.metadata=&#39;[{&quot;customizations&quot;: {&quot;vscode&quot;: {&quot;extensions&quot;: [&quot;ms-python.python&quot;]}}}]&#39;</pre><p>When a tool opens a container built from this image, it automatically merges this embedded config with any local devcontainer.json. This makes images self-describing — you don&#39;t need a separate config file to get the right extensions when using a prebuilt image.</p><h3>GitHub Codespaces Integration</h3><p>Dev containers are the underlying technology for GitHub Codespaces. The same devcontainer.json that works locally in VS Code works in Codespaces with no changes.</p><pre>{<br>  // Codespaces-specific: minimum machine requirements<br>  &quot;hostRequirements&quot;: {<br>    &quot;cpus&quot;: 4,<br>    &quot;memory&quot;: &quot;8gb&quot;,<br>    &quot;storage&quot;: &quot;32gb&quot;<br>  },<br>  // Codespaces-specific: badge-like port<br>  &quot;portsAttributes&quot;: {<br>    &quot;8000&quot;: {<br>      &quot;onAutoForward&quot;: &quot;openBrowser&quot;,<br>      &quot;label&quot;: &quot;Web App&quot;<br>    }<br>  }<br>}</pre><p>The hostRequirements property tells cloud services like Codespaces the minimum compute specs needed. They&#39;ll automatically select an appropriate machine type — and warn you if the requested specs aren&#39;t met.</p><h3>Pre-Building Images for Speed</h3><p>The biggest complaint about dev containers is the first-open time — building the image can take several minutes. The solution is pre-building.</p><pre># .github/workflows/prebuild.yml<br>name: Pre-build Dev Container<br>on:<br>  push:<br>    branches: [main]<br>    paths: [&#39;.devcontainer/**&#39;]<br><br>jobs:<br>  prebuild:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br>      - name: Pre-build and push<br>        uses: devcontainers/ci@v0.3<br>        with:<br>          imageName: ghcr.io/your-org/your-repo-devcontainer<br>          cacheFrom: ghcr.io/your-org/your-repo-devcontainer<br>          push: always</pre><pre>// .devcontainer/devcontainer.json<br>{<br>  // Reference the pre-built image<br>  &quot;image&quot;: &quot;ghcr.io/your-org/your-repo-devcontainer:latest&quot;,<br><br>  // Still apply lifecycle scripts at runtime<br>  &quot;postCreateCommand&quot;: &quot;pip install -r requirements.txt&quot;<br>}</pre><p>With this setup, when anyone opens the dev container, Docker pulls the pre-built image (cached in the registry) instead of building from scratch. First-open goes from 3–5 minutes to under 30 seconds.</p><h3>Supporting Tools: Not Just VS Code</h3><p>The Dev Container Specification is open and tool-agnostic. Any editor or service can implement it:</p><p>Tool Support <strong>VS Code</strong> First-party, full support via Dev Containers extension <strong>GitHub Codespaces</strong> Built on dev containers natively <strong>JetBrains IDEs</strong> Dev containers support in Gateway (remote development) <strong>Cursor</strong> Supports Dev Containers via the VS Code extension model <strong>GitHub Actions</strong> devcontainers/ci GitHub Action <strong>Azure DevOps</strong> devcontainers/ci Azure DevOps Task <strong>Gitpod</strong> Supports devcontainer.json as a Gitpod configuration source <strong>Dev Container CLI</strong> Reference implementation, tool-agnostic</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lQIpT6LQB6Afkb3K2awpHg.png" /><figcaption>Supporting Tools</figcaption></figure><h3>Templates: Start From Zero in Seconds</h3><p>If you don’t have a devcontainer.json yet, you don&#39;t have to write one from scratch. VS Code offers a full gallery of templates:</p><ol><li>Open Command Palette → <strong>“Dev Containers: Add Dev Container Configuration Files…”</strong></li><li>Choose a template (Python, Node, Go, Rust, Java, etc.)</li><li>Select any additional Features</li><li>Done — devcontainer.json (and optionally a Dockerfile) is generated</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ohJxHsxbmlGLAu2fLLT34g.png" /><figcaption>DevContainers Templates</figcaption></figure><h3>Common Patterns and Tips</h3><h3>Persist bash/zsh history across rebuilds</h3><pre>{<br>  &quot;mounts&quot;: [<br>    {<br>      &quot;source&quot;: &quot;devcontainer-bashhistory-${devcontainerId}&quot;,<br>      &quot;target&quot;: &quot;/commandhistory&quot;,<br>      &quot;type&quot;: &quot;volume&quot;<br>    }<br>  ],<br>  &quot;remoteEnv&quot;: {<br>    &quot;PROMPT_COMMAND&quot;: &quot;history -a&quot;,<br>    &quot;HISTFILE&quot;: &quot;/commandhistory/.bash_history&quot;<br>  }<br>}</pre><h3>dotfiles support</h3><p>VS Code Dev Containers can automatically clone and apply your personal dotfiles (.bashrc, .gitconfig, etc.) inside every container:</p><pre>// VS Code user settings (not devcontainer.json)<br>{<br>  &quot;dotfiles.repository&quot;: &quot;https://github.com/yourusername/dotfiles&quot;,<br>  &quot;dotfiles.targetPath&quot;: &quot;~/dotfiles&quot;,<br>  &quot;dotfiles.installCommand&quot;: &quot;~/dotfiles/install.sh&quot;<br>}</pre><h3>Non-root user</h3><p>All Microsoft dev container base images include a vscode user. Always prefer running as non-root:</p><pre>{<br>  &quot;remoteUser&quot;: &quot;vscode&quot;<br>}</pre><h3>Dev Containers vs. The Alternatives</h3><p><strong>vs. virtualenv / venv:</strong> Python virtual environments isolate Python packages but nothing else — you still need the right Python version, system libraries, and tools on your host. Dev containers isolate everything, including the OS.</p><p><strong>vs. Docker alone:</strong> Running docker run gives you a container, but not an interactive development workflow. No editor integration, no extension management, no lifecycle scripts. Dev containers are the layer that turns a Docker container into a full IDE experience.</p><p><strong>vs. Vagrant:</strong> Vagrant provisions VMs, which are heavier and slower than containers. Dev containers use Docker’s union filesystem and are typically much faster to start and rebuild. Vagrant is still valid for scenarios requiring true hardware isolation.</p><p><strong>vs. Nix / devenv:</strong> Nix provides reproducible environments at the package level. It’s powerful for ensuring exact tool versions without containers. The trade-off: steeper learning curve, less editor integration out of the box. Many teams use Nix + dev containers together (Nix inside the container).</p><p><strong>vs. GitHub Codespaces alone:</strong> Codespaces <em>is</em> dev containers running in the cloud. Using dev containers locally gives you the same environment without requiring internet access or incurring cloud costs.</p><h3>Where to Go From Here 📚</h3><ul><li>📖 <a href="https://containers.dev/">containers.dev</a> — the official spec site, with reference docs, features gallery, and templates</li><li>📋 <a href="https://containers.dev/implementors/json_reference/">devcontainer.json reference</a> — every property documented</li><li>🧩 <a href="https://containers.dev/features">Available Features</a> — searchable gallery of installable Features</li><li>📐 <a href="https://containers.dev/templates">Available Templates</a> — starter configs for every stack</li><li>💻 <a href="https://code.visualstudio.com/docs/devcontainers/containers">VS Code Dev Containers docs</a> — VS Code specific guide</li><li>🎬 <a href="https://www.youtube.com/playlist?list=PLj6YeMhvp2S5G_X6ZyMc8gfXPMFPg3O31">VS Code Dev Containers YouTube series</a> — the official “Dev Containers How To” playlist</li><li>🔧 <a href="https://github.com/devcontainers/cli">Dev Container CLI</a> — CLI reference implementation</li><li>🏗️ <a href="https://github.com/devcontainers/ci">devcontainers/ci</a> — GitHub Action and Azure DevOps Task</li></ul><h3>Wrapping Up</h3><p>Dev containers are one of those things that feel like overhead until the first time a teammate says “I cloned the repo and everything just worked.” Then they feel obvious.</p><p>The spec is elegant: one JSON file, a clear set of lifecycle hooks, a modular Features system, and editor integrations that handle everything else automatically. The mental overhead of managing different environments across different machines, different operating systems, and different CI systems — it just goes away.</p><p>Whether you’re a solo developer who moves between machines, a team lead who wants consistent onboarding, or a platform engineer building reproducible CI environments, dev containers solve a real problem in a way that scales from zero to very large teams.</p><p>Open Command Palette. Type “Add Dev Container”. Pick Python. Hit Enter. You’ve got 30 seconds. 🚀</p><p><em>Last updated April 2026. All configuration examples are based on the official Dev Container Specification at </em><a href="https://containers.dev/"><em>containers.dev</em></a><em>. For the latest reference, always check the official docs.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec2a982e2f9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[mypy — Make Python’s Type Hints Actually Do Something]]></title>
            <link>https://kapildagur.medium.com/mypy-make-pythons-type-hints-actually-do-something-b131c3f4d8cf?source=rss-7755415cbdb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b131c3f4d8cf</guid>
            <category><![CDATA[typing]]></category>
            <category><![CDATA[typed]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[mypy]]></category>
            <category><![CDATA[statically-typed]]></category>
            <dc:creator><![CDATA[Kapil Dagur]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 07:59:28 GMT</pubDate>
            <atom:updated>2026-03-15T07:59:28.508Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A complete guide to static type checking in Python: from your first annotation to strict mode, Protocols, TypedDict, mypyc, and everything new in mypy 1.19.</em> 🔍</p><p>Here’s a scenario you’ve probably lived through.</p><p>You write a function. It works. You call it from somewhere else six weeks later, pass in a None by accident, and get a beautiful AttributeError: &#39;NoneType&#39; object has no attribute &#39;strip&#39; at 4pm on a Friday. You spend 20 minutes tracing back through the call chain wondering where the None came from.</p><p>Now here’s the thing — Python <em>knew</em> that could happen. You just didn’t ask it to tell you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*b5HT2kd82c3GwIE4tJk7Qg.png" /></figure><p><strong>mypy</strong> is the tool that asks. It reads your Python type annotations and reasons about your code <em>before</em> you run it, catching exactly these kinds of bugs at the point where you wrote the mistake — not at 4pm on a Friday when a user hits it.</p><p>As of <strong>mypy 1.19.1</strong> (December 2025), mypy is faster and more capable than ever. This guide walks you through everything: why type checking matters, how to read and write annotations, every major feature, the modern Python typing ecosystem, and what’s new in recent releases.</p><h3>Wait — Doesn’t Python Already Have Type Hints?</h3><p>Yes! Python has had type annotations since Python 3.5 (PEP 484). You can write this:</p><pre>def greet(name: str) -&gt; str:<br>    return &quot;Hello, &quot; + name</pre><p>And Python… completely ignores those annotations at runtime. They’re just metadata. Nothing stops you from calling greet(42) — Python will happily try to concatenate &quot;Hello, &quot; with 42 and crash.</p><p>That’s where mypy comes in. mypy is a <strong>static type checker</strong> — it reads your annotations and your code, and <em>before you run anything</em>, it tells you where types don’t match up. It’s like a spell-checker for your type logic.</p><p>The best part: it’s entirely optional and incremental. You can add it to an existing project file by file, line by line. No big rewrite needed.</p><h3>Installation</h3><pre>pip install mypy<br># or with uv<br>uv add mypy --dev</pre><p>Check your version:</p><pre>uv run mypy --version<br># mypy 1.19.1 (compiled: yes)</pre><p>The (compiled: yes) means you&#39;re using the mypyc-compiled binary — significantly faster than the pure Python version.</p><h3>Your First Type-Checked File</h3><pre># greet.py</pre><pre>def greet(name: str) -&gt; str:<br>    return &quot;Hello, &quot; + name<br>result = greet(&quot;Alice&quot;)   # ✅ fine<br>wrong  = greet(42)        # ❌ mypy will catch this</pre><p>Run mypy:</p><pre>uv run mypy src/topic_mypy/greet.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_p3kuThVzl6okzQX93b_ag.png" /></figure><p>That’s mypy’s core value proposition — it found the bug before you ran the code. No test needed, no runtime, no user report.</p><h3>Reading mypy’s Output</h3><p>mypy errors follow a consistent format:</p><pre>filename.py:LINE: error: MESSAGE  [ERROR-CODE]</pre><p>For example:</p><pre>src/topic_mypy/greet.py:4: error: Argument 1 to &quot;greet&quot; has incompatible type &quot;int&quot;; expected &quot;str&quot;  [arg-type]<br>Found 1 error in 1 file (checked 1 source file)</pre><ul><li><strong>greet.py:4</strong> — exactly where the problem is</li><li><strong>error:</strong> — severity (could also be warning: or note:)</li><li><strong>[arg-type]</strong> — the error code, which you can use to selectively ignore or filter errors</li></ul><p>Clean, precise, and actionable. This is one of mypy’s real strengths — the error messages are genuinely readable.</p><h3>The Basic Type Annotations</h3><h3>Built-in types</h3><pre>name: str = &quot;Alice&quot;<br>age: int = 30<br>height: float = 5.9<br>active: bool = True<br>data: bytes = b&quot;hello&quot;</pre><h3>Collections</h3><pre># Modern syntax (Python 3.9+) — no need to import from typing<br>names: list[str] = [&quot;Alice&quot;, &quot;Bob&quot;]<br>scores: dict[str, int] = {&quot;Alice&quot;: 95, &quot;Bob&quot;: 87}<br>coords: tuple[float, float] = (1.0, 2.0)<br>unique: set[str] = {&quot;a&quot;, &quot;b&quot;, &quot;c&quot;}</pre><pre># Variable-length tuple<br>items: tuple[int, ...] = (1, 2, 3, 4)</pre><h3>Optional values (None-able)</h3><pre># These two are equivalent — use | syntax in Python 3.10+<br>from typing import Optional<br><br><br>def find_user(user_id: int) -&gt; Optional[str]:  # classic<br>    ...<br><br>def find_user(user_id: int) -&gt; str | None:     # modern, preferred<br>    ...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*teoU0s18StEXbDH-VHO7KQ.png" /><figcaption>With Naming conflict</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rsacIuXvfVBkxOaAtX8A-A.png" /><figcaption>Non Naming conflict</figcaption></figure><p>Optional[str] means &quot;either a str or None.&quot; This is one of the most important annotations — it forces you to handle the None case explicitly everywhere you use the return value.</p><h3>Union types</h3><pre>from typing import Union<br><br><br># Old style<br>def process(value: Union[str, int]) -&gt; str: ...<br><br># Modern style (Python 3.10+)<br>def process_(value: str | int) -&gt; str: ...</pre><h3>Function Annotations in Depth</h3><pre>from collections.abc import Callable, Iterator, Generator<br><br><br># A function that takes another function as an argument<br>def apply(func: Callable[[int], str], value: int) -&gt; str:<br>    return func(value)<br><br># A generator function<br>def count_up(start: int) -&gt; Generator[int, None, None]:<br>    while True:<br>        yield start<br>        start += 1<br><br># *args and **kwargs<br>def log(*args: str, **kwargs: int) -&gt; None:<br>    ...<br><br># Return nothing<br>def setup() -&gt; None:<br>    ...</pre><h3>TypedDict: Typing Your Dictionaries 📖</h3><p>One of the most practically useful features for real-world code. If you pass dictionaries around as structured data, TypedDict gives mypy the structure to check against:</p><pre>from typing import TypedDict<br><br><br>class UserConfig(TypedDict):<br>    name: str<br>    age: int<br>    email: str<br><br>def send_welcome(config: UserConfig) -&gt; None:<br>    print(f&quot;Welcome, {config[&#39;name&#39;]}!&quot;)<br>    print(f&quot;Sending to {config[&#39;email&#39;]}&quot;)<br><br># ✅ Fine<br>send_welcome({&quot;name&quot;: &quot;Alice&quot;, &quot;age&quot;: 30, &quot;email&quot;: &quot;alice@example.com&quot;})<br># ❌ mypy error: missing key &#39;email&#39;<br>send_welcome({&quot;name&quot;: &quot;Bob&quot;, &quot;age&quot;: 25})<br># ❌ mypy error: value of &#39;age&#39; has wrong type (str instead of int)<br>send_welcome({&quot;name&quot;: &quot;Carol&quot;, &quot;age&quot;: &quot;thirty&quot;, &quot;email&quot;: &quot;carol@example.com&quot;})</pre><p>You can also mark some keys as optional:</p><pre>from typing import TypedDict, NotRequired<br><br><br>class UserConfig(TypedDict):<br>    name: str<br>    email: str<br>    age: NotRequired[int]   # this key doesn&#39;t have to be present</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kSSlCDcT0OMRkmE7x7fmlA.png" /></figure><h3>dataclasses and Type Safety</h3><p>Python’s dataclasses work beautifully with mypy:</p><pre>from dataclasses import dataclass, field<br><br><br>@dataclass<br>class Product:<br>    name: str<br>    price: float<br>    tags: list[str] = field(default_factory=list)<br>    in_stock: bool = True<br># mypy knows the types of all fields<br>p = Product(name=&quot;Widget&quot;, price=9.99)<br>print(p.price + 1)    # ✅ float + int, fine<br>print(p.price + &quot;1&quot;)  # ❌ mypy error: can&#39;t add float and str</pre><p>Since you’re writing the field types anyway with dataclasses, mypy coverage comes almost for free.</p><h3>Protocols: Duck Typing With Type Safety 🦆</h3><p>This is one of mypy’s most powerful — and underused — features. In Python, you don’t need to inherit from a class to be “compatible” with it. If an object has the right methods, it works. Protocols let you express this pattern with full type safety.</p><pre>from typing import Protocol<br><br><br>class Drawable(Protocol):<br>    def draw(self) -&gt; None: ...<br>    def resize(self, factor: float) -&gt; None: ...<br>class Circle:<br>    def draw(self) -&gt; None:<br>        print(&quot;Drawing circle&quot;)<br>    def resize(self, factor: float) -&gt; None:<br>        self.radius *= factor<br>class Square:<br>    def draw(self) -&gt; None:<br>        print(&quot;Drawing square&quot;)<br>    def resize(self, factor: float) -&gt; None:<br>        self.side *= factor<br># Works with any object that has draw() and resize()<br>def render(shape: Drawable) -&gt; None:<br>    shape.draw()<br>render(Circle())   # ✅<br>render(Square())   # ✅<br>render(&quot;hello&quot;)    # ❌ mypy error: str doesn&#39;t have draw/resize</pre><p>Circle and Square don&#39;t inherit from Drawable. They don&#39;t even know about it. As long as they structurally match the Protocol, mypy considers them compatible. This is <strong>structural subtyping</strong> — Python&#39;s natural duck-typing, made statically verifiable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wu280TWnNXMCflSYdmSpsw.png" /></figure><h3>Generics: Writing Flexible, Type-Safe Code</h3><pre>from typing import TypeVar, Generic<br><br><br>T = TypeVar(&quot;T&quot;)<br><br>class Stack(Generic[T]):<br>    def __init__(self) -&gt; None:<br>        self._items: list[T] = []<br><br>    def push(self, item: T) -&gt; None:<br>        self._items.append(item)<br><br>    def pop(self) -&gt; T:<br>        return self._items.pop()<br><br>if __name__ == &#39;__main__&#39;:    <br>    int_stack: Stack[int] = Stack()<br>    int_stack.push(1)<br>    int_stack.push(2)<br>    value: int = int_stack.pop()   # mypy knows this is int<br>    int_stack.push(&quot;hello&quot;)  # ❌ mypy error: expected int, got str</pre><p>Python 3.12 introduced the new, cleaner generic syntax:</p><pre># Python 3.12+ syntax — no TypeVar import needed<br>class Stack[T]:<br>    def __init__(self) -&gt; None:<br>        self._items: list[T] = []<br><br>    def push(self, item: T) -&gt; None:<br>        self._items.append(item)<br><br>    def pop(self) -&gt; T:<br>        return self._items.pop()</pre><h3>Narrowing: mypy Follows Your Logic</h3><p>One of mypy’s genuinely impressive capabilities is <strong>type narrowing</strong> — it tracks how isinstance checks, if conditions, and assert statements change what types are possible at each point in your code.</p><pre>def process(value: str | int | None) -&gt; str:<br>    if value is None:<br>        return &quot;nothing&quot;<br>    # mypy knows: value is str | int here<br>    <br>    if isinstance(value, int):<br>            return str(value * 2)<br>        # mypy knows: value is str here<br>        return value.upper()  # ✅ mypy is certain this is str<br><br># assert also narrows<br>def get_user(user_id: int) -&gt; str | None:<br>    ...<br><br><br>if __name__ == &#39;__main__&#39;:<br>    user = get_user(1)<br>    assert user is not None   # mypy narrows to str after this line<br>    print(user.upper())       # ✅ safe</pre><p>This is what makes mypy feel smart rather than just pedantic. It doesn’t just match types mechanically — it reasons about your code’s control flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MTzkHLmNB1CpSC2pMUj4Aw.png" /></figure><h3>Literal Types: When a Value Matters, Not Just the Type</h3><pre>from typing import Literal<br><br><br>Direction = Literal[&quot;north&quot;, &quot;south&quot;, &quot;east&quot;, &quot;west&quot;]<br>def move(direction: Direction) -&gt; None:<br>    print(f&quot;Moving {direction}&quot;)<br>move(&quot;north&quot;)    # ✅<br>move(&quot;up&quot;)       # ❌ mypy error: &quot;up&quot; is not a valid Direction<br><br># Great for status codes, modes, states<br>Status = Literal[&quot;pending&quot;, &quot;active&quot;, &quot;cancelled&quot;]<br><br>def update_order(order_id: int, status: Status) -&gt; None:<br>    ...<br><br>update_order(1, &quot;active&quot;)     # ✅<br>update_order(1, &quot;deleted&quot;)    # ❌ mypy catches the typo</pre><p>Literal is excellent for preventing magic string bugs — the kind where you typo a status value and it silently does nothing until you notice the data is wrong.</p><h3>Final and ClassVar</h3><pre>from typing import Final, ClassVar<br><br><br>MAX_RETRIES: Final = 3              # cannot be reassigned<br>MAX_RETRIES = 5                     # ❌ mypy error: cannot assign to Final<br>class Config:<br>    debug: ClassVar[bool] = False   # class-level, not instance-level<br>    name: str                       # instance-level<br>Config.debug = True                 # ✅ ClassVar, fine<br>instance = Config()<br>instance.debug = True               # ❌ mypy error: cannot assign to ClassVar via instance</pre><h3>cast and # type: ignore: Escape Hatches</h3><p>Sometimes you know more than mypy does. These are your escape valves:</p><pre>from typing import cast<br><br><br># You know the return type, mypy doesn&#39;t<br>result = cast(str, some_opaque_function())<br># Suppress a specific error on one line<br>x = legacy_function()  # type: ignore[return-value]<br># Suppress all errors on one line (use sparingly)<br>x = legacy_function()  # type: ignore</pre><p># type: ignore[error-code] is preferred over bare # type: ignore — being specific means you&#39;ll notice if the underlying issue changes. mypy 1.15+ warns about unused # type: ignore comments when you pass --warn-unused-ignores, which helps you clean them up over time.</p><h3>🆕 mypy 1.18: ~40% Performance Boost</h3><p>mypy 1.18 delivered roughly a 40% speedup compared to 1.17 when type checking mypy itself, with some extreme cases showing improvements of 10× or higher. This came from a combination of type caching optimizations and mypyc-level improvements.</p><p>For large codebases where mypy was previously slow enough to feel like a CI bottleneck, this is a meaningful change.</p><h3>🆕 mypy 1.18/1.19: Binary Cache Format</h3><p>mypy 1.18 introduced a new binary fixed-format cache as an experimental feature. In mypy 1.19, this feature graduated from experimental — the team is planning to enable it by default in mypy 1.20.</p><p>Enable it now:</p><pre>mypy --fixed-format-cache myapp/</pre><p>Or in config:</p><pre>[mypy]<br>fixed_format_cache = true</pre><p>The binary cache makes incremental builds up to twice as fast and uses less space than the original JSON-based format. For large monorepos or projects with long incremental check times, this is worth enabling today.</p><h3>🆕 mypy 1.19: Disjoint Bases (PEP 800)</h3><p>mypy 1.19 added support for disjoint bases via PEP 800 — it recognizes the @disjoint_base decorator and rejects class definitions that combine mutually incompatible base classes.</p><pre>from typing import disjoint_base<br><br><br>@disjoint_base<br>class A: ...<br>@disjoint_base<br>class B: ...<br>class C(A, B): ...   # ❌ mypy error: A and B are disjoint, cannot combine</pre><p>This is useful for modeling mutually exclusive taxonomies — database backends, serialization formats, platform-specific implementations — where combining base classes is semantically meaningless.</p><h3>🆕 mypy 1.15: --strict-bytes Flag</h3><p>By default, mypy treats bytearray and memoryview as assignable to the bytes type for historical reasons. mypy 1.15 introduced --strict-bytes to disable this behavior, aligned with PEP 688 — and this flag will become the default in mypy 2.0.</p><pre>mypy --strict-bytes myapp/</pre><p>If you work with binary data and want accurate type checking for bytes-like types, enable this now rather than waiting for it to be a breaking change in 2.0.</p><h3>Configuration: pyproject.toml</h3><pre># pyproject.toml<br>[tool.mypy]<br>python_version = &quot;3.12&quot;<br>strict = true<br>warn_return_any = true<br>warn_unused_ignores = true<br>warn_redundant_casts = true<br>no_implicit_reexport = true<br>show_error_codes = true<br>pretty = true<br><br># Per-module overrides (great for gradual adoption)<br>[[tool.mypy.overrides]]<br>module = &quot;legacy_module.*&quot;<br>ignore_errors = true<br>[[tool.mypy.overrides]]<br>module = &quot;tests.*&quot;<br>disallow_untyped_defs = false</pre><p>The strict flag is a shorthand that enables a bundle of strict checks:</p><p>Flag enabled by strict What it catches disallow_untyped_defs Functions with missing annotations disallow_any_generics Generic types used without parameters (e.g., list not list[str]) warn_return_any Returning Any when a specific type is expected no_implicit_optional Parameters defaulting to None must be Optional explicitly strict_equality Nonsensical equality comparisons between incompatible types</p><p>Start with strict = false and individual flags. Graduate to strict = true when your codebase is fully annotated.</p><h3>Gradual Typing: The Practical Adoption Path</h3><p>mypy is designed for incremental adoption. You don’t type-check all or nothing.</p><p><strong>Step 1: Start with </strong><strong>--ignore-missing-imports</strong> Many third-party libraries don&#39;t ship type stubs yet. This flag stops mypy from complaining about them.</p><pre>mypy myapp/ --ignore-missing-imports</pre><p><strong>Step 2: Run mypy per-file or per-module</strong></p><pre>mypy myapp/models.py          # just one file<br>mypy myapp/services/          # just one directory</pre><p><strong>Step 3: Use </strong><strong># type: ignore to silence legacy problem spots</strong> Mark the known-bad lines and move on. You can come back and fix them later.</p><p><strong>Step 4: Enable stricter flags one at a time</strong></p><pre>mypy myapp/ --disallow-untyped-defs    # annotate all functions first<br>mypy myapp/ --warn-return-any          # next step<br>mypy myapp/ --strict                   # eventual goal</pre><p><strong>Step 5: Track coverage with mypy’s stats</strong></p><pre>mypy myapp/ --any-exprs-report .</pre><p>This produces a report showing what percentage of your codebase is Any (untyped) — a useful metric to track over time.</p><h3>Stub Files: When Libraries Don’t Have Types</h3><p>If a library doesn’t ship types, you have a few options:</p><p><strong>1. Install a stubs package (most common)</strong></p><pre>pip install pandas-stubs<br>pip install types-requests<br>pip install types-PyYAML</pre><p>Many popular libraries have community-maintained stubs in the typeshed project or separately on PyPI as types-* packages.</p><p><strong>2. Write your own stub file</strong></p><pre># requests.pyi (stub for a module)<br>from typing import Any<br><br><br>def get(url: str, **kwargs: Any) -&gt; Response: ...<br><br>def post(url: str, **kwargs: Any) -&gt; Response: ...<br><br>class Response:<br>    status_code: int<br>    text: str<br>    def json(self) -&gt; Any: ...</pre><p><strong>3. Use </strong><strong>py.typed marker</strong> If you&#39;re a library author, add an empty py.typed file to your package to tell mypy and other checkers that your library ships inline types:</p><pre>mypackage/<br>├── __init__.py<br>├── py.typed      ← empty file, signals type-checker support<br>└── core.py</pre><h3>Running mypy in CI</h3><pre># GitHub Actions<br>- name: Type check<br>  run: mypy myapp/ --strict<br><br># Or with uvx for zero-install<br>- name: Type check<br>  run: uvx mypy myapp/ --strict<br><br># Pre-commit hook (.pre-commit-config.yaml)<br>repos:<br>  - repo: https://github.com/pre-commit/mirrors-mypy<br>    rev: v1.19.1<br>    hooks:<br>      - id: mypy<br>        additional_dependencies: [types-requests, pandas-stubs]</pre><h3>mypyc: Compile Python to C Extensions</h3><p>This one is genuinely cool. mypy ships with <strong>mypyc</strong>, a compiler that uses your type annotations to compile Python modules into C extensions — often achieving 2–5× speedups with zero code changes.</p><pre>pip install mypy[mypyc]</pre><pre># Compile a module<br>mypyc myapp/hot_path.py<br><br># Run — Python automatically loads the compiled .so file<br>python -c &quot;import myapp.hot_path&quot;</pre><p>mypy itself is compiled with mypyc, which is why (compiled: yes) matters in the version output. If you have CPU-bound Python code with complete type annotations, mypyc is worth benchmarking.</p><h3>mypy vs. The Alternatives</h3><p><strong>vs. Pyright / Pylance:</strong> Pyright (Microsoft, powers Pylance in VS Code) is mypy’s strongest competitor. It’s faster for large codebases and has better IDE integration by default. Where mypy wins: it’s been around longer, has broader community adoption, more mature plugin support, and mypyc for compilation. Most teams pick one and stick with it. Pyright has stricter defaults in some areas; mypy is more configurable for gradual adoption.</p><p><strong>vs. Pytype (Google):</strong> Google’s type inference tool. Does more automatic inference (can type-check unannotated code) but slower and less widely adopted. Good for legacy codebases with no annotations.</p><p><strong>vs. Pyre (Meta):</strong> Meta’s type checker, written in OCaml. Very fast, designed for massive monorepos. Harder to set up outside Meta’s toolchain.</p><p><strong>vs. Ruff’s type linting:</strong> Ruff checks <em>some</em> type-annotation-related patterns (as lint rules) but is not a type checker. mypy and Ruff are complementary — use both.</p><p>The honest summary: <strong>mypy or Pyright</strong> for most teams. If you’re on VS Code and want the best IDE experience right now, Pyright/Pylance is excellent. If you want CI integration, plugin support (Django, Pydantic, SQLAlchemy), and mypyc, mypy is the richer ecosystem.</p><h3>mypy Plugins: Framework-Aware Type Checking</h3><p>mypy supports plugins that teach it the type semantics of specific frameworks:</p><pre>[tool.mypy]<br>plugins = [<br>    &quot;mypy_django_plugin.main&quot;,<br>    &quot;pydantic.mypy&quot;,<br>]</pre><p><strong>django-stubs + mypy-django-plugin</strong> — understands QuerySet types, model fields, request.user, and more. Without the plugin, mypy treats Django ORM operations as returning Any.</p><p><strong>pydantic.mypy</strong> — understands Pydantic model fields, validators, and model_config. Pydantic v2 ships with first-class mypy support built in.</p><p><strong>SQLAlchemy</strong> — sqlalchemy[mypy] adds a plugin that understands mapped columns and relationships.</p><h3>Real-World Workflow</h3><p>Here’s what a fully typed FastAPI project looks like with mypy:</p><pre># models.py<br>from pydantic import BaseModel<br>from typing import Annotated<br>from datetime import datetime<br><br><br>class UserCreate(BaseModel):<br>    name: str<br>    email: str<br>    age: int | None = None<br><br>class UserResponse(BaseModel):<br>    id: int<br>    name: str<br>    email: str<br>    created_at: datetime</pre><pre># services.py<br>from .models import UserCreate, UserResponse<br>from .database import Session<br><br><br>def create_user(db: Session, data: UserCreate) -&gt; UserResponse:<br>    user = db.add_user(<br>        name=data.name,<br>        email=data.email,<br>        age=data.age,<br>    )<br>    return UserResponse(<br>        id=user.id,<br>        name=user.name,<br>        email=user.email,<br>        created_at=user.created_at,<br>    )</pre><pre># app.py<br>from fastapi import FastAPI, Depends<br>from .services import create_user<br>from .models import UserCreate, UserResponse<br><br><br>app = FastAPI()<br>@app.post(&quot;/users&quot;, response_model=UserResponse)<br>def register(data: UserCreate, db=Depends(get_db)) -&gt; UserResponse:<br>    return create_user(db, data)</pre><pre>mypy . --strict<br># Success: no issues found in 8 source files</pre><p>The entire request/response cycle is type-safe. If you change UserCreate to make a field optional, mypy immediately tells you everywhere in your codebase that assumed the field was always present.</p><h3>The Commands You’ll Actually Use</h3><pre># Basic check<br>mypy myapp/<br><br># Check a single file<br>mypy myapp/services.py<br><br># Strict mode (recommended for greenfield projects)<br>mypy myapp/ --strict<br><br># Show error codes (helps with targeted ignores)<br>mypy myapp/ --show-error-codes<br><br># Pretty output (more readable in terminal)<br>mypy myapp/ --pretty<br><br># Check what Python version you&#39;re targeting<br>mypy myapp/ --python-version 3.12<br><br># Enable binary cache (faster incremental runs)<br>mypy myapp/ --fixed-format-cache<br><br># Show column numbers in errors<br>mypy myapp/ --show-column-numbers<br><br># Generate an HTML type coverage report<br>mypy myapp/ --html-report mypy-report/<br>open mypy-report/index.html</pre><h3>Where to Go From Here 📚</h3><ul><li>📖 <a href="https://mypy.readthedocs.io/">Official mypy docs</a> — the “Type system reference” section is excellent</li><li>🐍 <a href="https://peps.python.org/pep-0484/">PEP 484</a> — the original type hints PEP, readable and foundational</li><li>📰 <a href="https://mypy-lang.blogspot.com/">mypy blog</a> — release posts explain every new feature clearly</li><li>📕 <em>Robust Python</em> by Patrick Viafore — the best book on Python type safety in practice</li><li>🔌 <a href="https://github.com/python/typeshed">typeshed</a> — the community stub repository for standard library and popular packages</li><li>💬 <a href="https://github.com/python/mypy/discussions">mypy GitHub Discussions</a> — active and helpful</li><li>🎙️ Adam Johnson’s <a href="https://adamj.eu/">adamj.eu</a> — great mypy tips for Django specifically</li></ul><h3>Wrapping Up</h3><p>Type checking is one of those things that seems like overhead until you’ve had it save you from a nasty production bug. Then it becomes one of those things you don’t want to work without.</p><p>mypy doesn’t require you to change how Python feels to write. You’re still writing Python. You’re just writing Python that’s a little more honest about what it expects and what it returns — and mypy rewards that honesty by catching a whole category of bugs before they ever reach your users.</p><p>With mypy 1.18 and 1.19 bringing major performance improvements, a faster binary cache format, and PEP 800 support, the experience has genuinely never been better. The gradual adoption path means there’s no excuse not to start today, even on an existing codebase.</p><p>Start with one file. Run mypy yourfile.py. See what it says. That&#39;s all it takes to begin. 🚀</p><p><em>Last updated March 2026 — mypy 1.19.1. Questions or thoughts? Drop them in the comments below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b131c3f4d8cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[pytest — The Python Testing Framework That Actually Makes You Want to Write Tests]]></title>
            <link>https://kapildagur.medium.com/pytest-the-python-testing-framework-that-actually-makes-you-want-to-write-tests-1c0ea4bbe464?source=rss-7755415cbdb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c0ea4bbe464</guid>
            <category><![CDATA[pytest-framework]]></category>
            <category><![CDATA[pytest-fixtures]]></category>
            <category><![CDATA[pytest]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Kapil Dagur]]></dc:creator>
            <pubDate>Sat, 07 Mar 2026 06:21:43 GMT</pubDate>
            <atom:updated>2026-03-07T06:23:36.806Z</atom:updated>
            <content:encoded><![CDATA[<p><em>From your very first </em><em>assert to fixtures, parametrize, mocking, plugins, and everything new in pytest 9.0. A practical guide with no boring bits.</em> 🧪</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*kGr2byVyrR2oKGy-YYw1Jw.png" /></figure><p>Raise your hand if you’ve skipped writing tests because the setup felt like more work than the feature itself. 🙋</p><p>No judgment — we’ve all been there. You write a function, it works in the REPL, ship it, move on. And then two weeks later something breaks in a completely unrelated place and you spend two hours figuring out why.</p><p>That’s the real cost of untested code. Not the bugs you find immediately — those are easy. It’s the bugs that appear <em>later</em>, in <em>unexpected places</em>, that eat your time.</p><p><strong>pytest</strong> is the testing framework that removes the friction between “I should write tests” and actually writing them. No boilerplate classes, no self.assertEqual, no ceremony. Just Python functions, plain assert statements, and a powerful engine underneath that makes your failures readable, your setup reusable, and your test suite genuinely manageable as it grows.</p><p>As of <strong>pytest 9.0.2</strong> (December 2025, requires Python ≥ 3.10), there’s never been a better time to get started or level up.</p><h3>Why pytest over unittest? 🤔</h3><p>Python ships with unittest built-in, so why install anything else?</p><p>Here’s the same test written both ways:</p><pre># unittest style<br>import unittest<br><br><br>class TestMath(unittest.TestCase):<br>    def test_addition(self):<br>        self.assertEqual(1 + 1, 2)<br>    def test_type_error(self):<br>        with self.assertRaises(TypeError):<br>            &quot;string&quot; + 1</pre><pre># pytest style<br>def test_addition():<br>    assert 1 + 1 == 2</pre><pre>def test_type_error():<br>    import pytest<br>    with pytest.raises(TypeError):<br>        &quot;string&quot; + 1</pre><p>The pytest version is just… Python. No class inheritance, no special assertion methods to memorize, no boilerplate. And when something <em>fails</em>, pytest’s error messages are dramatically more informative than unittest’s.</p><p>pytest also runs unittest-style tests without any changes, so switching doesn&#39;t mean rewriting your existing suite.</p><h3>Installation &amp; First Run</h3><pre>pip install pytest<br># or with uv (faster ⚡)<br>uv add pytest --dev</pre><p>Check your version:</p><pre>pytest --version<br># pytest 9.0.2</pre><p>Create your first test file:</p><pre># test_calculator.py</pre><pre>def add(a, b):<br>    return a + b<br>def test_add():<br>    assert add(2, 3) == 5<br>def test_add_negative():<br>    assert add(-1, 1) == 0<br>def test_add_floats():<br>    assert add(1.5, 2.5) == 4.0</pre><p>Run it:</p><pre>pytest test_calculator.py<br># or just<br>pytest</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_f891K8EZ9CQQNOFjpSfYQ.png" /></figure><p>pytest automatically discovers any file named test_*.py or *_test.py and any function named test_* inside it. Zero configuration needed to get started.</p><h3>Reading the Output</h3><p>One of pytest’s biggest selling points is its failure messages. When a test fails, pytest doesn’t just tell you <em>that</em> it failed — it shows you <em>what</em> the values actually were.</p><pre>def test_add_wrong():<br>    assert add(2, 2) == 5</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VAmZjnIoXCRn2Nb6oEPSYw.png" /></figure><p>Compare that to unittest’s AssertionError: 4 != 5. pytest shows you the full expression breakdown. For complex objects like dicts and lists, it even diffs them side by side.</p><h3>Fixtures: The Heart of pytest ❤️</h3><p>If you learn one pytest concept deeply, make it fixtures. They are the key to writing tests that are clean, reusable, and maintainable.</p><p>A fixture is just a function decorated with @pytest.fixture. Any test that names it as a parameter gets the return value automatically.</p><pre>import pytest</pre><pre>@pytest.fixture<br>def sample_user():<br>    return {&quot;name&quot;: &quot;Alice&quot;, &quot;age&quot;: 30, &quot;email&quot;: &quot;alice@example.com&quot;}<br>def test_user_name(sample_user):<br>    assert sample_user[&quot;name&quot;] == &quot;Alice&quot;<br>def test_user_email(sample_user):<br>    assert sample_user[&quot;email&quot;] == &quot;alice@example.com&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LzCHhOCnEugypsw8Tf4nMg.png" /></figure><p>pytest sees that test_user_name has a parameter called sample_user, finds the fixture with that name, runs it, and passes the result in. Both tests get a fresh copy of the dictionary.</p><h3>Fixtures with Setup and Teardown</h3><p>Need to open a resource before a test and close it after? Use yield:</p><pre>@pytest.fixture<br>def db_connection():<br>    conn = create_database_connection()    # setup<br>    yield conn                             # test runs here<br>    conn.close()                           # teardown (always runs)</pre><p>This replaces setUp/tearDown in unittest — and it&#39;s much cleaner because the setup and teardown live together in one place.</p><h3>Fixture Scope: How Long Should They Live?</h3><p>By default, a fixture is created fresh for every test. You can change this:</p><pre>@pytest.fixture(scope=&quot;module&quot;)    # once per test file<br>def expensive_setup():<br>    return initialize_heavy_resource()</pre><pre>@pytest.fixture(scope=&quot;session&quot;)   # once for the entire test run<br>def global_config():<br>    return load_config()</pre><p>Scope Created Destroyed function (default) before each test after each test class once per test class after the class module once per test file after the file session once per pytest run at the end</p><p>Use session scope for things like database connections, API clients, or anything expensive to initialize. Use function scope for anything that should be isolated between tests.</p><h3>Fixture Composition</h3><p>Fixtures can depend on other fixtures — just add them as parameters:</p><pre>@pytest.fixture<br>def db():<br>    return setup_database()</pre><pre>@pytest.fixture<br>def logged_in_user(db):        # db fixture is injected automatically<br>    user = db.create_user(&quot;alice&quot;)<br>    db.login(user)<br>    return user<br>def test_user_dashboard(logged_in_user):<br>    assert logged_in_user.is_logged_in == True</pre><p>pytest resolves the dependency graph for you. This composability is what makes fixtures so powerful for larger test suites.</p><h3>conftest.py: Sharing Fixtures Across Files</h3><p>When multiple test files need the same fixtures, put them in a conftest.py file. pytest discovers it automatically — no imports needed.</p><pre>my_project/<br>├── src/<br>|   ...<br>├── tests/<br>│   ├── conftest.py            ← shared fixtures live here<br>│   ├── test_calculator.py<br>│   ├── test_user.py<br>│   └── test_products.py</pre><pre># conftest.py<br>import pytest</pre><pre>@pytest.fixture(scope=&quot;session&quot;)<br>def api_client():<br>    client = create_test_client()<br>    yield client<br>    client.teardown()</pre><p>Every test in every file under that directory can now use api_client as a parameter. No imports, no boilerplate — pytest handles discovery.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4msYu0eNy2bHoTi18q5fJA.png" /></figure><h3>Parametrize: Test Many Inputs, Write Once 🔢</h3><p>One of pytest’s most-used features. Instead of copy-pasting the same test with different values:</p><pre># 😩 the tedious way<br>def test_add_positive():<br>    assert add(1, 2) == 3</pre><pre>def test_add_zero():<br>    assert add(0, 5) == 5<br>def test_add_negative():<br>    assert add(-1, 1) == 0</pre><p>Use @pytest.mark.parametrize:</p><pre># 😍 the pytest way<br>@pytest.mark.parametrize(&quot;a, b, expected&quot;, [<br>    (1, 2, 3),<br>    (0, 5, 5),<br>    (-1, 1, 0),<br>    (100, -50, 50),<br>])<br>def test_add(a, b, expected):<br>    assert add(a, b) == expected</pre><p>This runs 4 separate tests, each with its own pass/fail status. If the third case fails, the first two still show as passing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0N8Pug0TRjXvr7xEVtI4Ng.png" /></figure><p>You can also parametrize over more complex objects, use pytest.param for individual test IDs, and combine parametrize with fixtures.</p><h3>🆕 pytest 9.0: Subtests — The New Kid</h3><p>pytest 9.0 (November 2025) merged the popular pytest-subtests plugin into core. Subtests are a powerful alternative to parametrize for when you don&#39;t know the test cases until runtime.</p><pre>def test_all_users_have_emails(subtests):<br>    users = fetch_users_from_db()    # could be any number</pre><pre>for user in users:<br>        with subtests.test(name=user.name, msg=f&quot;User {user.name} missing email&quot;):<br>            assert user.email is not None</pre><p>With @pytest.mark.parametrize, all test cases must be known at collection time. Subtests let you generate them dynamically during the test itself — which is essential when you&#39;re iterating over database records, API responses, or any runtime data.</p><p>If one subtest fails, the others continue running and are reported individually. It’s the best of both worlds: a single logical test with independent failure reporting per case.</p><h3>Marking Tests: Skip, XFail, and Custom Marks 🏷️</h3><h3>Skip a test</h3><pre>import sys</pre><pre>@pytest.mark.skip(reason=&quot;Not implemented yet&quot;)<br>def test_future_feature():<br>    assert do_something_not_ready()<br>@pytest.mark.skipif(sys.platform == &quot;win32&quot;, reason=&quot;Linux only&quot;)<br>def test_linux_specific():<br>    assert check_linux_thing()</pre><h3>Expected failures (xfail)</h3><pre>@pytest.mark.xfail(reason=&quot;Known bug, tracked in issue #42&quot;)<br>def test_known_broken():<br>    assert broken_function() == &quot;expected&quot;</pre><p>If the test fails → reported as xfail (expected, no alarm). If it <em>passes</em> → reported as xpass (unexpected pass — you should fix the mark!). With strict_xfail = true in your config, unexpected passes actually <em>fail</em> the suite, which is the right behavior in most projects.</p><h3>Custom marks</h3><pre># Declare in pyproject.toml<br># [tool.pytest]<br># markers = [&quot;slow: marks tests as slow&quot;, &quot;integration: requires external services&quot;]</pre><pre>@pytest.mark.slow<br>def test_something_heavy():<br>    ...<br>@pytest.mark.integration<br>def test_against_real_api():<br>    ...</pre><p>Run only specific marks:</p><pre>pytest -m slow           # only slow tests<br>pytest -m &quot;not slow&quot;     # skip slow tests (great for quick local runs)<br>pytest -m integration    # only integration tests</pre><p>This pattern is really useful in CI: run fast unit tests on every push, integration tests only on merges to main.</p><h3>Testing Exceptions</h3><pre>def divide(a, b):<br>    if b == 0:<br>        raise ValueError(&quot;Cannot divide by zero&quot;)<br>    return a / b</pre><pre>def test_divide_by_zero():<br>    with pytest.raises(ValueError, match=&quot;Cannot divide by zero&quot;):<br>        divide(10, 0)<br>def test_exception_details():<br>    with pytest.raises(ValueError) as exc_info:<br>        divide(10, 0)<br>    assert &quot;zero&quot; in str(exc_info.value)</pre><p>The match parameter takes a regex and checks the exception message — a small detail that saves you from tests that pass for the wrong exception type.</p><h3>Mocking with monkeypatch and unittest.mock</h3><h3>monkeypatch (pytest’s built-in)</h3><pre>def test_env_variable(monkeypatch):<br>    monkeypatch.setenv(&quot;API_KEY&quot;, &quot;test-key-123&quot;)<br>    assert get_api_key() == &quot;test-key-123&quot;</pre><pre>def test_patch_function(monkeypatch):<br>    monkeypatch.setattr(&quot;mymodule.requests.get&quot;, lambda url: MockResponse())<br>    result = fetch_data(&quot;https://api.example.com&quot;)<br>    assert result is not None</pre><p>monkeypatch automatically reverts all patches after each test — no cleanup needed.</p><h3>unittest.mock (for more complex mocking)</h3><pre>from unittest.mock import MagicMock, patch</pre><pre>def test_email_sent():<br>    with patch(&quot;myapp.email.send_email&quot;) as mock_send:<br>        mock_send.return_value = True<br>        result = register_user(&quot;alice@example.com&quot;)<br>        mock_send.assert_called_once_with(&quot;alice@example.com&quot;, subject=&quot;Welcome!&quot;)<br>        assert result is True</pre><p>Both approaches work well in pytest. monkeypatch is lighter and very clean for simple cases; unittest.mock is more powerful for complex interactions.</p><h3>🆕 pytest 9.0: Native TOML Configuration</h3><p>Before pytest 9.0, configuring pytest in pyproject.toml used a quirky &quot;INI compatibility mode&quot; where everything was treated as a string. Now pytest has proper native TOML support:</p><pre># pyproject.toml — pytest 9.0+ native TOML config<br>[tool.pytest]<br>minversion = &quot;9.0&quot;<br>testpaths = [&quot;tests&quot;, &quot;integration&quot;]<br>addopts = [&quot;-ra&quot;, &quot;-q&quot;, &quot;--strict-markers&quot;]</pre><pre># Proper types now - no more string workarounds!<br>log_level = &quot;INFO&quot;<br>timeout = 30<br># Strict mode (new unified strictness in 9.0)<br>strict = true<br>[tool.pytest.markers]<br>slow = &quot;marks tests as slow (use -m &#39;not slow&#39; to skip)&quot;<br>integration = &quot;marks tests requiring external services&quot;</pre><p>The old [tool.pytest.ini_options] table still works — both can&#39;t be used simultaneously, but migration is straightforward.</p><p>You can also now use a standalone pytest.toml or .pytest.toml file if you prefer keeping it separate from pyproject.toml.</p><h3>🆕 pytest 9.0: Unified Strict Mode</h3><p>pytest 9.0 consolidated all the individual strict flags under one unified strict option:</p><pre>[tool.pytest]<br>strict = true   # enables all of the below:<br>                # strict_config (unknown config options = error)<br>                # strict_markers (undeclared markers = error)<br>                # strict_parametrization_ids (duplicate IDs = error)<br>                # strict_xfail (unexpected xpass = error)</pre><p>This is excellent practice for mature projects. Undeclared markers, duplicate parametrize IDs, misconfigured options — these previously caused silent weirdness. Now they’re hard errors. Enable it and fix the warnings; your test suite will be cleaner for it.</p><h3>Temporary Files and Directories</h3><p>pytest provides built-in fixtures for working with the filesystem safely:</p><pre>def test_write_and_read(tmp_path):<br>    # tmp_path is a pathlib.Path to a unique temp directory<br>    file = tmp_path / &quot;output.txt&quot;<br>    file.write_text(&quot;hello pytest&quot;)<br>    assert file.read_text() == &quot;hello pytest&quot;</pre><pre>def test_multiple_files(tmp_path):<br>    (tmp_path / &quot;data&quot;).mkdir()<br>    config = tmp_path / &quot;config.json&quot;<br>    config.write_text(&#39;{&quot;debug&quot;: true}&#39;)<br>    assert config.exists()</pre><p>The directory is automatically cleaned up after the test. tmp_path_factory is the session-scoped version for fixtures that need to share a temp directory.</p><h3>Running Tests: The Commands You’ll Actually Use</h3><pre># Run all tests<br>pytest</pre><pre># Run a specific file<br>pytest tests/test_users.py</pre><pre># Run a specific test function<br>pytest tests/test_users.py::test_user_creation</pre><pre># Run a specific parametrized case<br>pytest tests/test_users.py::test_add[1-2-3]</pre><pre># Verbose output (shows each test name)<br>pytest -v</pre><pre># Show extra summary (failures, errors, skips, xfails)<br>pytest -ra</pre><pre># Stop after first failure<br>pytest -x</pre><pre># Stop after N failures<br>pytest --maxfail=3</pre><pre># Run only tests matching a keyword<br>pytest -k &quot;user and not admin&quot;</pre><pre># Run marked tests<br>pytest -m slow</pre><pre># Show print() output (normally captured)<br>pytest -s</pre><pre># Last failed tests only (huge timesaver)<br>pytest --lf</pre><pre># Failed first, then rest<br>pytest --ff</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H5BWMoktzM4yc4XktM-xqw.png" /></figure><p>--lf (last failed) is one of the most useful flags in day-to-day development. After fixing a bug, you want to immediately re-run only the tests that were failing — not wait for the whole suite.</p><h3>Coverage: Are You Actually Testing Your Code?</h3><pre>pip install pytest-cov</pre><pre>pytest --cov=myapp --cov-report=term-missing</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a_zSIbVsoKFRDS8mIt278Q.png" /></figure><pre># HTML report (much nicer for larger projects)<br>pytest --cov=myapp --cov-report=html<br>open htmlcov/index.html</pre><p>The HTML report lets you click into individual files and see exactly which lines are not covered. This is much more actionable than just a percentage.</p><pre># pyproject.toml — set a minimum coverage threshold<br>[tool.coverage.report]<br>fail_under = 80</pre><p>Now pytest --cov=myapp will fail if coverage drops below 80%. Great for CI gates.</p><h3>Parallel Test Execution</h3><pre>pip install pytest-xdist<br>pytest -n auto     # use all available CPU cores<br>pytest -n 4        # use exactly 4 workers</pre><p>For large test suites, this can cut your run time dramatically — often 2–4× faster on a typical developer machine. Tests need to be independent (no shared state between tests) for this to work correctly, which is good practice anyway.</p><h3>Testing Async Code</h3><pre>pip install pytest-asyncio</pre><pre>import pytest</pre><pre>@pytest.mark.asyncio<br>async def test_async_function():<br>    result = await fetch_data_async()<br>    assert result is not None<br># Or configure globally in pyproject.toml:<br># [tool.pytest]<br># asyncio_mode = &quot;auto&quot;</pre><p>With asyncio_mode = &quot;auto&quot;, all async def test_* functions are automatically treated as async tests — no decorator needed.</p><h3>The Essential Plugin Ecosystem</h3><p>pytest has a rich plugin ecosystem. These are the ones worth knowing:</p><p>Plugin What it does pytest-cov Code coverage reports pytest-xdist Parallel test execution pytest-asyncio Testing async/await code pytest-mock Cleaner MagicMock integration pytest-django Django integration (db fixtures, client, etc.) pytest-httpx Mock httpx requests pytest-benchmark Performance benchmarking in tests pytest-randomly Randomize test order (finds ordering dependencies) pytest-timeout Fail tests that take too long pytest-snapshot Snapshot testing for complex outputs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q9CGl0GUCCrkTcwalOD0aw.png" /></figure><h3>A Real-World Test Structure</h3><p>Here’s what a well-organized pytest project actually looks like:</p><pre>my_project/<br>├── src/<br>│   └── myapp/<br>│       ├── models.py<br>│       ├── services.py<br>│       └── utils.py<br>├── tests/<br>│   ├── conftest.py          ← session/module fixtures<br>│   ├── unit/<br>│   │   ├── conftest.py      ← unit test fixtures<br>│   │   ├── test_models.py<br>│   │   └── test_utils.py<br>│   ├── integration/<br>│   │   ├── conftest.py      ← integration fixtures (real DB, etc.)<br>│   │   └── test_api.py<br>│   └── e2e/<br>│       └── test_flows.py<br>└── pyproject.toml</pre><pre># pyproject.toml<br>[tool.pytest]<br>testpaths = [&quot;tests&quot;]<br>addopts = [&quot;-ra&quot;, &quot;-q&quot;]<br>strict = true<br><br>markers = [<br>    &quot;unit: fast isolated unit tests&quot;,<br>    &quot;integration: tests requiring database/external services&quot;,<br>    &quot;e2e: full end-to-end tests&quot;,<br>]</pre><pre># Different test runs for different purposes<br>pytest -m unit                   # quick local feedback<br>pytest -m &quot;unit or integration&quot;  # pre-push<br>pytest                           # full suite in CI</pre><h3>pytest vs. The Alternatives</h3><p><strong>vs. unittest:</strong> unittest is built-in and solid — it’s what pytest itself can run. But its class-based structure, verbose assertion methods, and weaker failure messages make it harder to write and maintain. pytest wins on developer experience, hands down.</p><p><strong>vs. nose / nose2:</strong> nose was the popular pytest alternative for years. It’s effectively unmaintained now. nose2 is an improvement but hasn’t gained the same community momentum. pytest is the clear default choice.</p><p><strong>vs. Hypothesis:</strong> Hypothesis isn’t really a competitor — it’s a property-based testing library that works <em>with</em> pytest. Instead of specifying exact input values, you describe the properties your function should have, and Hypothesis generates inputs to try to break them. It pairs beautifully with pytest and is worth exploring once you’re comfortable with pytest’s basics.</p><p><strong>vs. Robot Framework:</strong> Robot Framework is for acceptance testing and uses a keyword-driven, non-Python DSL. It has its place in QA automation workflows. For unit and integration testing in Python codebases, pytest is the more natural fit.</p><h3>Where to Go From Here 📚</h3><ul><li>📖 <a href="https://docs.pytest.org/">Official pytest docs</a> — excellent, especially the “How-to guides” section</li><li>🎓 <a href="https://testandcode.com/">Test &amp; Code podcast</a> — Brian Okken literally wrote the book on pytest</li><li>📕 <em>Python Testing with pytest</em> by Brian Okken — the go-to book, covers everything</li><li>🔌 <a href="https://docs.pytest.org/en/stable/reference/plugin_list.html">pytest plugin list</a> — 1000+ plugins indexed</li><li>💬 <a href="https://github.com/pytest-dev/pytest/discussions">pytest GitHub Discussions</a> — active and welcoming</li><li>📰 Adam Johnson’s blog <a href="https://adamj.eu/">adamj.eu</a> — lots of practical pytest tips for Django projects</li></ul><h3>Wrapping Up</h3><p>pytest’s philosophy is elegant: tests should be easy to write, easy to read, and when they fail, their failures should be easy to understand. Everything else — fixtures, parametrize, plugins, the whole ecosystem — is in service of that philosophy.</p><p>The barrier to getting started is genuinely low. You write Python functions, you use assert, and pytest handles the rest. The ceiling is also high — the same framework scales to thousands of tests with complex setups, parallel execution, and coverage enforcement.</p><p>pytest 9.0 brought subtests, real TOML config, and unified strict mode — all quality-of-life improvements that make an already great tool better.</p><p>If you’ve been putting off building out your test suite, this is a good week to start. Your future self (debugging at 11pm six months from now) will thank you. ✨</p><p><em>Last updated March 2026 — pytest 9.0.2. Drop your questions in the comments — always happy to help!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c0ea4bbe464" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Meet UV— The Python Tool That Makes You Wonder Why You Ever Waited]]></title>
            <link>https://kapildagur.medium.com/meet-uv-the-python-tool-that-makes-you-wonder-why-you-ever-waited-dc0d91dd10bf?source=rss-7755415cbdb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc0d91dd10bf</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[package-management]]></category>
            <category><![CDATA[uv]]></category>
            <category><![CDATA[python-virtualenv]]></category>
            <dc:creator><![CDATA[Kapil Dagur]]></dc:creator>
            <pubDate>Tue, 24 Feb 2026 18:17:13 GMT</pubDate>
            <atom:updated>2026-03-07T04:30:25.336Z</atom:updated>
            <content:encoded><![CDATA[<p><em>One Rust-powered binary to replace pip, pyenv, virtualenv, pipx, and Poetry. Yes, really.</em></p><p>You know that feeling when you run pip install -r requirements.txt and just... wait? You check your phone, pour a coffee, come back, and there&#39;s a dependency conflict staring back at you. We&#39;ve all been there. 😅</p><p>This isn’t a pip complaint post. pip is genuinely great and has served the Python community for over a decade. But the ecosystem around Python package management has gotten <em>complicated</em> — pip for installing, virtualenv for isolation, pyenv for Python versions, pipx for global tools, Poetry for project management. That’s five tools with five different CLIs just to manage a project.</p><p><strong>uv</strong> came along and said: what if one tool did all of that, and did it fast?</p><p>Not “a little faster.” We’re talking 10–100× faster. Let’s dig in.</p><h3>What Even Is uv? 🤔</h3><p><strong><em>uv</em></strong> is a Python package manager and project management tool built by <a href="https://astral.sh/">Astral</a> — the same team behind Ruff (the fast Python linter). It’s written in Rust, ships as a single binary, and requires no Python to install.</p><p>Think of it as a Swiss Army knife for Python tooling:</p><pre><br>+-------------------------------------------+<br>|What you used before | uv replaces it with |<br>+---------------------+---------------------+<br>| pip                 | uv pip              |<br>| virtualenv/venv     | uv venv             |<br>| pip-tools           | uv pip compile      |<br>| pyenv               | uv python           |<br>| pipx                | uv tool / uvx       |<br>| Poetry / PDM        | uv init + uv add    |<br>+-------------------------------------------+</pre><p>The beautiful part? You don’t have to adopt all of these at once. Start with just the faster pip. Expand when you’re ready.</p><h3>Getting Started (Takes 10 Seconds)</h3><pre># macOS / Linux<br>curl -LsSf https://astral.sh/uv/install.sh | sh</pre><pre># Windows<br>powershell -c &quot;irm <a href="https://astral.sh/uv/install.ps1">https://astral.sh/uv/install.ps1</a> | iex&quot;</pre><pre># Already have Python? Just do this<br>pip install uv</pre><p>That’s it. Single binary, nothing else to configure.</p><h3>The “Just Make pip Faster” Path</h3><p>If you want zero workflow disruption, this is your entry point:</p><pre>uv pip install requests<br>uv pip install -r requirements.txt<br>uv pip uninstall requests<br>uv pip freeze</pre><p>Looks familiar, right? That’s intentional. uv’s pip interface is a drop-in replacement. The only thing that changes is the speed — and the first time you see a large requirements file install in under 2 seconds, you’ll feel it.</p><p><strong>Pro tip:</strong> You can literally alias it:</p><pre>alias pip=&quot;uv pip&quot;</pre><p>Done. You’re now using uv.</p><h3>But Wait — There’s a Lockfile Now 🔒</h3><p>Here’s where uv starts pulling ahead of plain pip. When you use uv for project management (more on that below), it generates a uv.lock file that captures your <em>entire</em> dependency tree — not just the top-level packages you declared, but everything those packages depend on, pinned to exact versions, and it works across all platforms.</p><p>This means:</p><ul><li>Your teammate clones the repo, runs uv sync, and gets <em>your exact environment</em></li><li>CI always runs the same versions</li><li>No more “works on my machine” moments 🎉</li></ul><h3>Full Project Management: The Good Stuff</h3><p>Let’s walk through creating a real project with uv from scratch.</p><pre>uv init my-cool-app<br>cd my-cool-app</pre><p>This creates a pyproject.toml, a uv.lock, and a .venv. You&#39;re ready to go.</p><p><strong>Adding dependencies:</strong></p><pre>uv add fastapi uvicorn          # production deps<br>uv add pytest httpx --dev       # dev-only deps<br>uv add ruff --group lint        # custom groups</pre><p><strong>Running your code:</strong></p><pre>uv run uvicorn main:app --reload<br>uv run pytest</pre><p>uv run automatically ensures your environment is in sync before running. No need to remember to activate a virtualenv. Just run. ✨</p><p><strong>Teammate onboarding:</strong></p><pre>git clone your-repo<br>cd your-repo<br>uv sync        # ← this is literally the whole setup<br>uv run python main.py</pre><p>One command to go from a fresh clone to a working, perfectly reproducible environment. That’s the dream.</p><h3>Python Version Management (Bye pyenv 👋)</h3><p>One of uv’s sneaky-good features:</p><pre>uv python install 3.12<br>uv python install 3.11 3.12 3.13    # install several at once<br>uv python list                       # see what&#39;s installed<br>uv python pin 3.12                   # pin this project to 3.12</pre><p>If you try to run a project that requires Python 3.11 and you don’t have it, uv offers to download it for you. Automatically. That kind of friction removal adds up over a career.</p><h3>That Wild “Self-Contained Script” Feature 🤯</h3><p>This one genuinely surprised me when I first saw it. PEP 723 allows you to declare a script’s dependencies <em>inside the script itself</em>:</p><pre># /// script<br># requires-python = &quot;&gt;=3.11&quot;<br># dependencies = [&quot;requests&quot;, &quot;rich&quot;]<br># ///</pre><pre>import requests<br>from rich import print</pre><pre>data = requests.get(&quot;https://api.github.com&quot;).json()<br>print(data)</pre><p>Run it with:</p><pre>uv run my_script.py</pre><p>uv reads the inline metadata, creates a temporary environment, installs the deps, runs the script, and cleans up. No requirements file, no virtualenv setup — just one self-contained file you can share with anyone. This is especially handy for data scripts, automation tasks, and quick utilities.</p><h3>Global Tool Management (The pipx Replacement)</h3><pre># Install a tool globally<br>uv tool install ruff<br>uv tool install black</pre><pre># Run a tool once without installing it<br>uvx ruff check .<br>uvx black --check .</pre><pre># Run a specific version<br>uvx ruff@0.6.0 check .</pre><p>uvx is genuinely one of the most satisfying commands in the tool. Need to run a formatter once? Don&#39;t pollute your environment — just uvx it.</p><h3>How Fast Is “Fast”? 📊</h3><p>Real numbers from the community:</p><ul><li>A typical FastAPI + Pydantic + Uvicorn stack: pip takes ~15 seconds cold. uv takes ~1 second cold, ~200ms warm.</li><li>Large ML project installs that pip takes 2–3 minutes: uv does in 10–15 seconds.</li><li>Virtual environment creation: uv is ~80× faster than vanilla venv.</li></ul><p>The warm cache numbers are what get me. Once you’ve installed a package once, subsequent installs across different projects are near-instant because uv caches wheels globally and uses copy-on-write on supported filesystems. It shares package data intelligently across projects without duplicating disk space.</p><h3>How Does It Compare to the Other Tools?</h3><p><strong>vs. pip:</strong> uv’s pip interface is strictly better for the same operations — faster, with optional lockfile support. pip remains important as the standard and for simplest use cases, but for daily development, uv pip is a direct upgrade.</p><p><strong>vs. Poetry:</strong> Poetry is mature and well-loved. uv’s project management draws significant inspiration from it. The key differences: uv is dramatically faster, manages Python versions natively, follows PEP standards more closely, and its lockfile is platform-independent (Poetry’s is platform-specific by default). If you like Poetry’s workflow, you’ll feel at home with uv.</p><p><strong>vs. PDM:</strong> Both follow PEP 621 and support dependency groups. uv is faster and broader in scope (the Python version management and pipx replacement make uv a more complete solution). PDM is excellent and still maintained.</p><p><strong>vs. Conda:</strong> Conda solves a different problem — managing non-Python system-level dependencies like CUDA libraries. If your project is pure PyPI packages, uv wins. If you need Conda’s binary dependency management, keep using Conda (or Mamba, which is Conda’s faster C++ rewrite).</p><p><strong>vs. pyenv:</strong> uv’s uv python commands cover ~90% of pyenv&#39;s daily use cases with the convenience of being built into the same tool. For most projects, you can drop pyenv entirely.</p><h3>Quick Docker/CI Reference</h3><pre># Dockerfile<br>COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/<br>COPY pyproject.toml uv.lock ./<br>RUN uv sync --frozen --no-dev</pre><pre># GitHub Actions<br>- uses: astral-sh/setup-uv@v4<br>- run: uv sync --frozen<br>- run: uv run pytest</pre><p>--frozen means &quot;use the lockfile exactly as committed, don&#39;t touch it.&quot; Perfect for reproducible CI.</p><h3>Migration Cheat Sheet</h3><p><strong>From pip + requirements.txt:</strong></p><pre>uv init<br>uv add $(cat requirements.txt | grep -v &#39;#&#39;)<br>uv lock</pre><p><strong>From Poetry:</strong></p><ul><li>Your pyproject.toml structure transfers fairly directly</li><li>Move deps from [tool.poetry.dependencies] to [project.dependencies]</li><li>Run uv lock to generate the new lockfile</li></ul><p><strong>Zero-risk path:</strong></p><pre>alias pip=&quot;uv pip&quot;<br># You&#39;re done. That&#39;s the whole migration.</pre><h3>Is It Production-Ready?</h3><p>Yes. uv is at version 0.9.x as of early 2026 and is deployed at scale by companies across the Python ecosystem. Astral maintains a clear stability policy, and the pip interface has been stable for quite a while. PyCharm added native uv support in 2024.3.2. VS Code recognizes uv environments automatically.</p><h3>Where to Go Next</h3><ul><li>📖 <a href="https://docs.astral.sh/uv">Official docs</a> — genuinely well-written</li><li>💻 <a href="https://github.com/astral-sh/uv">GitHub repo</a> — the releases tab is a great changelog</li><li>🎓 Real Python’s “Managing Python Projects With uv” — thorough tutorial-style walkthrough</li><li>🚀 Astral’s blog post on unified Python packaging — explains the design decisions behind uv</li></ul><h3>Final Thought</h3><p>uv doesn’t make you a better programmer. But it removes friction — the small, annoying, time-consuming friction that accumulates into real frustration over a long project. Faster installs, reproducible environments, one tool instead of five, and a teammate onboarding experience that’s actually pleasant.</p><p>pip laid the foundation. uv builds on everything the ecosystem learned and delivers the next version of that experience.</p><p>Give it ten minutes. Install it, try uvx ruff check . on your codebase, watch it run. Then try uv sync on your next project. I&#39;d be surprised if you go back. 🦀</p><p><em>Last updated February 2026 — uv 0.9.x. Got questions or feedback? Drop them in the comments!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc0d91dd10bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>