<?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 Kais Kawar on Medium]]></title>
        <description><![CDATA[Stories by Kais Kawar on Medium]]></description>
        <link>https://medium.com/@kaiskawar?source=rss-dd17e675eb45------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*COGPwPs_ZzYSmGU1bz5u5A.jpeg</url>
            <title>Stories by Kais Kawar on Medium</title>
            <link>https://medium.com/@kaiskawar?source=rss-dd17e675eb45------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 17:02:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kaiskawar/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[Pydantic vs Dataclasses: Define your Data Model]]></title>
            <link>https://medium.com/@kaiskawar/pydantic-vs-dataclasses-define-your-data-model-cb1c344faaa3?source=rss-dd17e675eb45------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb1c344faaa3</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pydantic]]></category>
            <category><![CDATA[data-class]]></category>
            <category><![CDATA[data-model]]></category>
            <dc:creator><![CDATA[Kais Kawar]]></dc:creator>
            <pubDate>Tue, 13 May 2025 12:04:40 GMT</pubDate>
            <atom:updated>2025-05-13T12:04:40.426Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*33UktqKqBWYUaqndtH7OQg.png" /><figcaption>AI Image depicting Pydantic Vs Dataclasses using prompts by Author created in GPT-4o</figcaption></figure><p>When working with data structures in Python, whether you’re building complex APIs, configuring applications, or simply structuring information, you’ll eventually face a choice between two powerful tools: <strong>Pydantic</strong> and <strong>dataclasses</strong>. Both offer elegant solutions for managing data, but they serve different purposes and come with distinct trade offs. Depending on your use case, one might suit you far better than the other.</p><p>This post is a quick comparison of both, focusing on the parts where they <em>really</em> behave differently.</p><h3>Pydantic: The Strict Gatekeeper</h3><p>Pydantic is a third-party library that takes Python’s type hints and enforces them during runtime. It doesn’t only suggest what your data should look like, instead, <em>it demands conformity</em>.</p><pre>from pydantic import BaseModel<br><br>class User(BaseModel):<br>    name: str<br>    age: int<br>    email: str<br><br># This works as expected<br>valid_user = User(name=&quot;Roman&quot;, age=57, email=&quot;roman@example.com&quot;)<br><br># This raises a validation error<br>invalid_user = User(name=&quot;Alex&quot;, age=&quot;thirty&quot;, email=&quot;alex@example.com&quot;)</pre><p>What I especially appreciate about Pydantic is its modular architecture. The main package stays slim while specialized functionality lives in separate libraries. Do you need email validation? Grab that specific package. Do you want settings management? There is a dedicated module for that. This approach keeps your dependencies light when you only need certain features.</p><h3>Dataclasses: Python’s Native Solution</h3><p>Introduced in <a href="https://docs.python.org/3/whatsnew/3.7.html#whatsnew37-pep557">Python 3.7</a>, dataclasses automate the creation of special methods like __init__(), __repr__(), and __eq__() based on your class attributes:</p><pre>from dataclasses import dataclass<br><br>@dataclass<br>class User:<br>    name: str<br>    age: int<br>    email: str<br><br># Both of these work, even with incorrect data types<br>user1 = User(&quot;Charlie&quot;, 25, &quot;charlie@example.com&quot;)<br>user2 = User(&quot;Dave&quot;, &quot;twenty-six&quot;, &quot;dave@example.com&quot;)</pre><p>Dataclasses provide you with a clean way to define data structures without writing boilerplate code, but they don’t perform type checking at runtime. Type hints are exactly that, a suggestion, and have no effect on script execution.</p><h3>Three Key Differences</h3><pre>┌──────────────────────┬────────────────────────────────┬────────────────────┐<br>│ Behavior             │ Pydantic                       │ Dataclass          │<br>├──────────────────────┼────────────────────────────────┼────────────────────┤<br>│ Type enforcement     │ Strictly enforced              │ Not enforced       │<br>│ Positional arguments │ Not allowed                    │ Allowed            │<br>│ Mutability           │ Immutable by default           │ Mutable by default │<br>│ Runtime validation   │ Yes                            │ No                 │<br>│ Lightweight          │ Optional features are separate │ Built-in           │<br>└──────────────────────┴────────────────────────────────┴────────────────────┘</pre><h4>1. Type Validation: Safety vs Speed</h4><p><em>Only Pydantic raises an error for type violations.</em> When you pass a string where an integer is expected, Pydantic will give a warning, while dataclasses will silently accept the incorrect type:</p><pre># Pydantic: Raises ValidationError<br>user = User(name=&quot;Alan&quot;, age=&quot;twenty-seven&quot;, email=&quot;alan@example.com&quot;)<br><br># Dataclass: Works fine even with a wrong type<br>user = User(name=&quot;Alan&quot;, age=&quot;twenty-seven&quot;, email=&quot;alan@example.com&quot;)</pre><p>This difference explains why our pipeline was accepting malformed data, we were using dataclasses where we needed Pydantic’s strict validation.</p><h4>2. Argument Handling: Named vs. Positional</h4><p><em>Only Pydantic requires named arguments</em>. Dataclasses happily accept positional arguments based on field order:</p><pre># Pydantic: Keyword arguments are a must<br>user = User(name=&quot;Frank&quot;, age=41, email=&quot;frank@example.com&quot;)<br><br># Dataclass: Positional arguments are allowed<br>user = User(&quot;Frank&quot;, 41, &quot;frank@example.com&quot;)</pre><p>This seems minor until you refactor your code and accidentally change the order of fields. With dataclasses, you might silently swap values into the positional arguments.</p><h4>3. Mutability: Fixed vs. Flexible</h4><p><em>Only dataclasses are mutable by default</em>. Once created, Pydantic model instances don’t allow attribute changes unless specifically configured:</p><pre># Dataclass: Can be modified after creation<br>user = User(&quot;Grace&quot;, 31, &quot;grace@example.com&quot;)<br>user.age = 32  # Works fine<br><br># Pydantic: Immutable by default<br>user = User(name=&quot;Grace&quot;, age=31, email=&quot;grace@example.com&quot;)<br>user.age = 32 # Raises error unless model is configured to be mutable</pre><p>This immutability in Pydantic can prevent bugs from accidental modifications but might surprise you if you’re expecting to update values later.</p><h4>When to Use Each?</h4><p>Choose <strong>Pydantic</strong> when:</p><ul><li>Data validation is critical</li><li>You’re working with external data (API responses, user input)</li><li>You need automatic parsing and type conversion</li><li>Documentation generation is important</li></ul><p>Choose <strong>dataclasses</strong> when:</p><ul><li>You need simple data containers with minimal overhead</li><li>Performance is a primary concern</li><li>You’re working with trusted data sources</li><li>Type checking will be handled elsewhere (like with a static type checker)</li></ul><h4>Final Thoughts</h4><p>So, when should you go for Pydantic, and when are dataclasses the right fit? As discussed above, it’s a matter of context and priorities.</p><p>Pydantic is your go-to for increasing your system’s resiliency especially when it has to interact with unpredictable data, offering stronger guarantees through runtime validation, and extensible packages to allow for additional tasks like email validation or settings management.</p><p>Conversely, Python’s built-in dataclasses shine in their simplicity and performance, ideal for internal data representation where strict validation might be overkill.</p><p>Both tools are powerful in the right context. Just know which job you’re hiring them for!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb1c344faaa3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A MySQL Date Function Mystery]]></title>
            <link>https://medium.com/@kaiskawar/a-mysql-date-function-mystery-56ac55ab8104?source=rss-dd17e675eb45------2</link>
            <guid isPermaLink="false">https://medium.com/p/56ac55ab8104</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[relational-databases]]></category>
            <category><![CDATA[database-development]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Kais Kawar]]></dc:creator>
            <pubDate>Sat, 12 Apr 2025 11:26:49 GMT</pubDate>
            <atom:updated>2025-04-21T16:09:24.179Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fNudAz57s6FYEoAL" /><figcaption>Photo by <a href="https://unsplash.com/@landb?utm_source=medium&amp;utm_medium=referral">Branko Stancevic</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Mystery of the Missing Data</h3><p>So there I was in January 2024, everything running fine until January 7th hit. I noticed that no new jobs were being added to our job_dedupe table. As a developer responsible for maintaining our data pipeline, this immediately caught my attention.</p><p>What made this particularly odd was that January 7th happened to be the first Sunday of the month. Was this just a coincidence, or was there something more to it?</p><h3>Digging Into The Code</h3><p>I started looking at the SQL code that was supposed to be grabbing jobs from different weeks:</p><pre>j.posted_at BETWEEN DATE_SUB(NOW(), INTERVAL (DAYOFWEEK(NOW()) - 1 + 7 * ({week_count})) DAY) <br>AND DATE_SUB(NOW(), INTERVAL (DAYOFWEEK(NOW()) - 1 + 7 * ({week_count}-1)) DAY)</pre><p>This query was supposed to select jobs posted from specific week intervals. But something was obviously broken. To troubleshoot, I ran some simple test queries:</p><pre>SELECT STR_TO_DATE(CONCAT(YEARWEEK(NOW() - INTERVAL 0 WEEK), &#39;Sunday&#39;), &#39;%x%v %W&#39;) - Output: 2024–01–07 <br>SELECT STR_TO_DATE(CONCAT(YEARWEEK(NOW() - INTERVAL 1 WEEK), &#39;Sunday&#39;), &#39;%x%v %W&#39;) - Output: 2024–01–07</pre><p>Wait a minute — both queries returned the same date! This explains why no new data was getting processed. Our query was essentially asking for data between January 7th and January 7th , a time window of zero days.</p><h3>Figuring Out What Went Wrong</h3><p>After banging my head against this for a while, I realized I was using the STR_TO_DATE function wrong. The issue boiled down to this:</p><ol><li>YEARWEEK() by default thinks weeks start on Sunday (that’s mode 0)</li><li>Our format string %x%v %W<strong> </strong>is meant for when weeks start on Monday (that’s mode 3)</li></ol><p>Here’s the break down of the format specifiers according to MySQL’s documentation:</p><pre>╔═══════════╦═════════════════════════════════════════════════════════════════════════╗<br>║ Specifier ║                               Description                               ║<br>╠═══════════╬═════════════════════════════════════════════════════════════════════════╣<br>║ %V        ║ Week (01–53) where Sunday is the first day; WEEK() mode 2; used with %X ║<br>║ %v        ║ Week (01–53) where Monday is the first day; WEEK() mode 3; used with %x ║<br>║ %X        ║ Year for week where Sunday is first day; used with %V                   ║<br>║ %x        ║ Year for week where Monday is first day; used with %v                   ║<br>║ %U        ║ Week (00–53) where Sunday is first day; WEEK() mode 0                   ║<br>║ %u        ║ Week (00–53) where Monday is first day; WEEK() mode 1                   ║<br>╚═══════════╩═════════════════════════════════════════════════════════════════════════╝</pre><p>Our code was using %x%v (Monday-first format) combined with the default YEARWEEK() function that uses Sunday-first mode. That’s why on January 7th, 2024, the system got confused and two different weeks ended up with the same Sunday.</p><h3>How I Fixed It</h3><p>Instead of trying to patch up the STR_TO_DATE approach, I went with something simpler and used DATE_SUB directly:</p><pre>DATE_SUB(NOW(), INTERVAL (DAYOFWEEK(NOW()) - 1 + 7 * {week_count}) DAY)</pre><p>This works more reliably because:</p><p>1. It figures out how many days have passed since the most recent Sunday using DAYOFWEEK(NOW()) — 1<br>2. If we want to go back more weeks, it adds 7 days for each week<br>3. Then it just subtracts that many days from today’s date</p><p>For example, if today is Wednesday (day 4 in MySQL’s day-of-week numbering), the calculations look like:</p><p>- (4–1) = 3 days since Sunday<br>- Subtract 3 days from today to get last Sunday<br>- If we want the Sunday from two weeks ago, we would add 7 * 2 = 14 to get 3 + 14 = 17 days to subtract</p><h3>Lessons Learned</h3><p>This incident has taught me a few important things when working with dates in database systems:</p><p>1. <strong>Be careful of format specifiers</strong>: Different date functions may use different conventions for what constitutes the “first day” of a week.<br>2. <strong>Test edge cases</strong>: Problems like this only show up at specific times, like the first week of a month or year.<br>3. <strong>Keep it simple when you can</strong>: Our new approach using DATE_SUB is way more straightforward and less likely to break in unexpected ways.<br>4. <strong>Understand the documentation</strong>: Turns out this exact issue has been in <a href="https://bugs.mysql.com/bug.php?id=66178">MySQL forums since 2012</a>. Oops.</p><p>The next time you’re working with date calculations in SQL, remember that little things like whether weeks start on Sunday or Monday can make a significant difference in your results — especially when different functions have different default behaviors!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56ac55ab8104" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>