<?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 Grigorii Osipov on Medium]]></title>
        <description><![CDATA[Stories by Grigorii Osipov on Medium]]></description>
        <link>https://medium.com/@grigorii.osipov?source=rss-bbf30c462a1b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*3Vmxabq_TQ7mUfPB</url>
            <title>Stories by Grigorii Osipov on Medium</title>
            <link>https://medium.com/@grigorii.osipov?source=rss-bbf30c462a1b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 12:48:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@grigorii.osipov/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[uv scripts: micro-production situationship]]></title>
            <link>https://medium.com/datamindedbe/uv-scripts-micro-production-situationship-1ab75ecfdfa8?source=rss-bbf30c462a1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ab75ecfdfa8</guid>
            <category><![CDATA[script]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[uv]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[pep723]]></category>
            <dc:creator><![CDATA[Grigorii Osipov]]></dc:creator>
            <pubDate>Tue, 26 May 2026 07:49:37 GMT</pubDate>
            <atom:updated>2026-05-26T07:49:37.081Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pdMkUUV2JxVzDEVcViYwjQ.png" /></figure><p>Sometimes you are not trying to start a Python project at all.</p><p>Sometimes you are just working in a Terraform repository, doing Terraform things, and then a small problem appears that Terraform alone does not solve elegantly. Not a big enough problem to justify a full Python package, but annoying enough that a quick script suddenly starts looking very reasonable.</p><p>That is where uv scripts started making a lot of sense to me.</p><p>Under the hood, this workflow is enabled by <a href="https://peps.python.org/pep-0723/">PEP 723</a>, which standardises inline script metadata. In practice though, the real experience is uv. It is the tool that makes the whole thing pleasant enough to actually use.</p><h3>When a small script does not justify a full Python setup</h3><p>Recently I worked in a Terraform repository where JSON configuration was generated through Terraform templates. The small version of that problem looks like this.</p><pre>variable &quot;project_name&quot; {<br>  default = &quot;ducklake&quot;<br>}<br><br>locals {<br>  config = templatefile(&quot;${path.module}/config.json&quot;, {<br>    project = var.project_name<br>  })<br>}</pre><pre>{<br>  &quot;service&quot;: &quot;${project}-api&quot;,<br>  &quot;environment&quot;: &quot;production&quot;<br>}</pre><p>Terraform fills in the variables and produces the final JSON used by the infrastructure code.</p><p>For a tiny JSON file, this is barely worth thinking about. For a multi-thousand-line Grafana dashboard adapted for deployment across multiple accounts, it becomes much more annoying.</p><p>At that point I wanted a small local helper script that could inspect the rendered output before shipping it. Then the script grew slightly more useful. It validated the JSON structure, extracted panel names, and compared the generated output against a known-good baseline.</p><p>This was useful enough to keep, but not important enough to turn the repository into a Python project.</p><p>That is the small niche where uv scripts fit extremely well.</p><h3>The overhead of a modern Python project</h3><p>A typical modern Python project might look something like this:</p><pre>├── .gitignore<br>├── CHANGELOG.md<br>├── README.md<br>├── VERSION.md<br>├── pyproject.toml<br>├── src<br>│   └── terraform_json_validator<br>│       ├── __init__.py<br>│       └── main.py<br>└── uv.lock</pre><p>This is already quite minimal by modern standards. I am not even listing tests, CI, documentation setup, editor config, or anything more ambitious.</p><p>Still, for a tiny utility script inside a Terraform repository, this is a lot.</p><p>To do it the conventional way, I would have to introduce multiple root-level files, project structure, packaging metadata, and all the usual Python machinery just to support one script. That is perfectly reasonable when the repository is actually a Python repository. It feels much less reasonable when the repository is primarily infrastructure code and the Python part exists only to solve one specific problem.</p><p>That is the part I find interesting. There is a huge gap between a throwaway one-off script and a full Python project. In reality, a lot of useful internal tooling lives somewhere in the middle.</p><h3>uv scripts as the middle ground</h3><p>I remembered a <a href="https://reddit.com/r/Python/comments/1jmyip9/selfcontained_python_scripts_with_uv/">Reddit post about one-off scripts</a> and went looking through the uv documentation. The suggested starting point was this:</p><p>uv init --script json_parser.py --python 3.12</p><p>That generates a file like this:</p><pre># /// script<br># requires-python = &quot;&gt;=3.12&quot;<br># dependencies = []<br># ///<br><br><br>def main() -&gt; None:<br>    print(&quot;Hello from json_parser.py!&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Instead of creating a separate pyproject.toml, the script carries its own metadata inline. The Python version, dependencies, and later even a lock file can all be tied directly to that one script.</p><p>Adding dependencies is just as straightforward:</p><p>uv add — script json_parser.py “requests&lt;3” “rich”</p><p>Which updates the metadata block directly inside the script:</p><pre># /// script<br># dependencies = [<br>#   &quot;requests&lt;3&quot;,<br>#   &quot;rich&quot;,<br># ]<br># ///<br>...</pre><p>That is a very neat balance. The script stays a script, but it is no longer pretending dependencies do not exist.</p><p>If package versions are particularly sensitive, they can also be locked:</p><p>uv lock --script json_parser.py</p><p>This produces a json_parser.py.lock file, which plays the same role as a normal uv.lock file in a regular project.</p><p>That matters more than it might initially seem. A one-file script is nice. A one-file script with reproducible dependencies is something I would be far happier to commit to a shared repository.</p><p>And to not forget, the explicit way to run the script is:</p><pre>uv run --script json_parser.py</pre><p>That is probably the clearest version for a shared repository. It makes the uv dependency obvious and does not hide too much behind Unix script behaviour. And if you still want to go all the way and make it feel properly script-like, you can add a shebang:</p><pre>#!/usr/bin/env -S uv run --script<br>#<br># /// script<br># requires-python = &quot;&gt;=3.12&quot;<br># dependencies = []<br># ///<br>...</pre><p>Then make it executable:</p><p>chmod +x json_parser.py</p><p>At that point, anyone with uv installed can run the file directly in fully script-like behaviour.</p><pre>./json_parser.py</pre><p>This is probably the one part where I am undecided. It is convenient, but it also hides some abstraction and assumes familiarity with uv. Whether that trade-off is acceptable depends on the team and the repository. I think it is fine as long as the repository makes that expectation clear.</p><h3>Small does not have to mean disposable</h3><p>Even if the script remains a single file, I still do not think that means it should be treated casually. Production code usually benefits from tests, linting, formatting, and type checking. For a small utility script, I would probably skip tests unless the logic grows large enough to justify them. The overhead can outweigh the value quite quickly.</p><p>However, I would not feel comfortable committing Python code to a shared repository without at least formatting, linting, and type checking. It is largely because these tools communicate intent. They make it clearer how the code should behave, how it should be structured, and what guarantees the author expects. In practice, that makes the script easier to read, easier to maintain, and much easier for both humans and automated tools to modify safely.</p><p>If a hook configuration already exists, I would just add to it. Otherwise, a small prek.toml <a href="https://github.com/grigsos/prek-uv-example/blob/bc3d4965d9a55d866753185f45d23c324ddf5089/prek.toml">file is enough</a>.</p><p>At this point, someone might reasonably ask whether this is overengineering for a simple script. I would say no, almost every time.</p><p>Spending an extra ten minutes to add formatting, linting, and type checking dramatically improves readability and maintainability. If the file is going to live in a shared repository and other people are expected to touch it, then it deserves at least that level of care.</p><h3>Why I like this pattern</h3><p>What I like about uv scripts is not just that they make small scripts easy. Plenty of things make small scripts easy.</p><p>What I like is that they make small scripts respectable.</p><p>They give you a middle ground between two extremes:</p><ul><li>a throwaway script with undocumented dependencies and vague expectations</li><li>a fully scaffolded Python project that feels disproportionate to the problem</li></ul><p>With uv scripts, a single file can still declare its Python version, manage its dependencies, lock them when needed, participate in formatting and linting, and sit comfortably inside a repository that is not otherwise Python-first.</p><h3>Conclusion</h3><p>In the end, this gives me something that feels production-adjacent without pretending to be a full application.</p><p>It lives as a single file, yet still benefits from dependency management, reproducibility, formatting, linting, and type checking. It can be executed directly, version-controlled alongside infrastructure code, and shared with coworkers without introducing a full Python project structure into a repository that does not need one.</p><p>I think that is the real appeal of uv scripts and yet another checkmark for reasons to use uv.</p><p>PEP 723 is what makes the inline metadata standard possible. uv is what makes it actually pleasant. And together they create a very practical sweet spot for what I can only describe as micro-production code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ab75ecfdfa8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datamindedbe/uv-scripts-micro-production-situationship-1ab75ecfdfa8">uv scripts: micro-production situationship</a> was originally published in <a href="https://medium.com/datamindedbe">Dataminded</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DuckLake Wants to Fix the Lakehouse. Can It?]]></title>
            <link>https://medium.com/datamindedbe/ducklake-wants-to-fix-the-lakehouse-can-it-fd0a65880ce6?source=rss-bbf30c462a1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd0a65880ce6</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[data-lakehouse]]></category>
            <category><![CDATA[ducklake]]></category>
            <category><![CDATA[duckdb]]></category>
            <dc:creator><![CDATA[Grigorii Osipov]]></dc:creator>
            <pubDate>Tue, 24 Mar 2026 09:19:41 GMT</pubDate>
            <atom:updated>2026-03-24T09:19:41.011Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wLuaotYQQOWiBtBXLkReBg.png" /></figure><p>While I was on the bench between projects at Dataminded, I had a chance to explore DuckLake and lakehouse architecture in more depth. A partner challenged me to think about how I would design and use it if I were the solution architect responsible for putting it into production. Rather than presenting a full architecture proposal, this article explores the design ideas behind DuckLake and the strengths and limitations I encountered while experimenting with it.</p><p>DuckLake promises something quite appealing: a much simpler version of a lakehouse, easy to set up and removing much of the complexity around modern lakehouse stacks. But does it actually deliver on that promise, and what trade-offs does that simplicity introduce? This article explores where DuckLake fits in the current lakehouse ecosystem, where it shines, and where the limitations currently lie.</p><h3>Recap on data lakehouses and DuckLake</h3><p>Data lakehouse is a relatively new evolution in data architecture designs, becoming popular in the late 2010s/early 2020s. If you are unfamiliar with the concept of a lakehouse, a good overview can be found in <a href="https://medium.com/@dasabhijith01/data-lakehouse-101-8707aa998efa">this</a> article on lakehouse background. It came to be a combination of data lakes (object storage) and data warehouses (table format), becoming something that is easily interacted with by users thanks to its table format and scalability due to object storage.</p><p>For a long time, I found the concept difficult to grasp because I did not yet understand how the broader data ecosystem fit together. If you consider the technologies used on their own, they are rather straightforward and easy to explain. However, when the time comes to piece together a complete architecture and understand how it works, it is not apparent.</p><p>What made it click for me was a <a href="https://www.linkedin.com/safety/go?url=https%3A%2F%2Fdocs.google.com%2Fpresentation%2Fd%2F1uTuscrjdnD-muGjtkZLVklkB5QAUU24I%2Fedit%3Fusp%3Dsharing%26ouid%3D102885351760309357520%26rtpof%3Dtrue%26sd%3Dtrue&amp;trk=flagship-messaging-web&amp;messageThreadUrn=urn%3Ali%3AmessagingThread%3A2-Njg2Y2NlZTgtYjZkNS00ZDE0LWJjNGYtYmZjZTc2NThlNTI2XzEwMA%3D%3D&amp;lipi=urn%3Ali%3Apage%3Ad_flagship3_messaging_conversation_detail%3ByddCAhstQ2q5VCzNNk5wZQ%3D%3D">presentation</a> by the CEO of LakeOps, a data lake optimisation company, where he explained the lakehouse concept as a summary of five choices (some possibly being multi-choice, such as file format or engines) at its core. It is possible to visualise the flow of data via it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TMW9OOZ1k48Rrc1wVnhAlQ.png" /><figcaption>You’ve decided on Apache Iceberg, Now What ? Speed, Efficiency and Cost in the Real World — <strong>Amit Gilad</strong> (slightly modified)</figcaption></figure><blockquote>A user wants to join users and orders writes a query using Spark. Spark queries the Glue catalog, which contains the metadata about the tables. The tables are stored in Iceberg table format on S3, formatted as Parquet files. The catalog returns all the necessary information for the engine to query the data, with pointers to Iceberg metadata. Spark then accesses the metadata and data files directly on S3, reads the data and performs the join, returning the result to the user.</blockquote><p>Ultimately, a lake house is an abstract concept, an architectural pattern. It is not a set of technologies that can be replicated every time, meaning that every design of a lakehouse will require assembling many independent components mentioned above, such as catalog, table formats and so on.</p><p>With addition of each component, both horizontally and vertically in the architecture, new possibilities emerge, but so do new potential bottlenecks and failure points. There is no true “one size fits all” solution, meaning that a lakehouse often becomes a stitched-together system, sometimes more smoothly than others.</p><h3>Why did DuckDB start the DuckLake initiative</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LJOlbuWt7sniC8YlO6RAEg.png" /></figure><p>DuckDB, known frequently as “SQLite for OLAP”, has been capitalizing on its success as a fantastic tool for single-node compute and storage, frequently being positioned as a front runner among MVP-style libraries, similar to polars . It is easy to use and quick to start. DuckLake appears to apply that same philosophy to lakehouse architecture.</p><h3>What DuckLake changes in the architecture</h3><p>DuckLake claims to create a lightweight version of a lakehouse that occupies two slots inside the big decisions chart, enabling a much tighter coupling which promises ease of use and faster initiation. The largest architectural change is to the table format itself, where metadata is kept in OLTP format rather than as manifests and log files in object storage. By doing so, metadata operations become both faster and fully ACID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BADsx2PGXGoFh9-yhc4GmA.png" /></figure><p>With this design, you are no longer tied to a single machine. By having a single catalog, data can easily be written, stored and read from anywhere. In short, DuckLake attempts to bring the same philosophy that made DuckDB popular: simplicity, fast setup and ease of use, to the lakehouse ecosystem.</p><p>If you have DuckDB installed on the local machine, the DuckLake website claims it is as simple as running as the following command:</p><pre>INSTALL ducklake;<br><br>ATTACH &#39;ducklake:metadata.ducklake&#39; AS my_ducklake;<br>USE my_ducklake;</pre><p>In practice, setting up a lakehouse in the cloud is a little more involved. I set up DuckLake environments on AWS for both solo (<a href="https://github.com/grigsos/ducklake-duckdb-local/">DuckDB</a>) and multi-client (<a href="https://github.com/grigsos/ducklake-postgres-aws/">PostgreSQL</a>) catalogs, including data attached to experiment with.</p><p>The reason these two setups exist is that the solo catalog is primarily intended for single-machine usage. In this configuration, the metadata is stored locally and DuckDB acts as both the compute engine and the catalog, which makes the setup extremely simple but also confines usage to a single machine.</p><p>The difference between the two is quite large in terms of complexity. The solo setup only requires an S3 bucket with read and write permissions, whereas the multi-client setup requires additional networking configuration and an RDS instance. The payoff of using PostgreSQL in the cloud, however, is worth it due to the simple fact that it finally becomes possible for a team of engineers to use DuckDB on their machines to connect to a single shared catalog and read and write data.</p><p>You can discover the differences in components required in the infra folder, with code required to set up the DuckLakes being found in src/main.py.</p><p>After experimenting with these setups, the natural question becomes what advantages this architectural approach actually provides.</p><h3>Strengths of the DuckLake approach</h3><ol><li><strong>Simpler setup compared to existing table formats</strong> — The table formats that are typically present are heavy, with big hitters such as Iceberg, Hudi and proprietary Delta Lake being difficult to start working with. While DuckLake could be set up in 2/3 lines, the above table formats require configuration of an ecosystem.</li><li><strong>Reduced architectural choices</strong> — By forcing the two choices of catalog and table format, DuckLake restricts the number of components that need to be configured, allowing architects and data engineers to spin up fully functional lakehouses much faster on demand.</li><li><strong>Metadata stored in relational databases</strong> — DuckLake moves the metadata, which contains pointers and manifest trees, into an (ideally) relational database, which massively speeds up metadata operations while keeping them ACID.</li></ol><p>Furthermore, DuckLake currently supports only Parquet, the de facto file format for tabular data storage. While it could support other file formats, in my albeit limited experience as a data engineer I have never felt the need to use alternatives or felt constrained by Parquet.</p><p>For storage locations, DuckLake supports all three hyperscalers, AWS, Azure and Google object storage, as well as NFS, so storage compatibility is generally not an issue.</p><p>Taken together, these design choices make the architecture appealing, especially for medium to large lakehouse deployments. However, as you might have already noticed, one major aspect has not yet been discussed: data engines, which is where the real limitation currently lies.</p><h3>Current ecosystem limitations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lYg5rGDfS2sgc90LNyb1lg.png" /><figcaption>Filled out DuckLake compatibility chart</figcaption></figure><p>The main limitation of DuckLake today is not architectural, but ecosystem support. Allowing existing data engines to interact nicely and bug-freely with a new piece of large software is not as easy as it seems. This means that work needs to be done by volunteers from either the DuckLake project or the data engines themselves to add this functionality to their code.</p><p>For the biggest example, you can currently run pipelines and push data to a DuckLake via DuckDB with no issues. However, if you wanted to connect it to a dashboard such as Power BI, it would be impossible. One of the most basic requirements for data analysts, presenting findings through dashboards, is therefore not yet feasible.</p><p>You could create workarounds by running a service in the middle that takes the requested query, passes it to DuckDB and returns the results. However, as mentioned, this would only mask the underlying issue.</p><p>And thus, adoption is currently the main factor preventing wider use. DuckLake will live or die by its ecosystem support, as the DuckDB team has already provided data engineers with the tools needed to work with a modern and easy-to-use lakehouse. At the moment only DuckDB fully supports DuckLake, while other engines are still playing catch-up in either alpha or beta stages.</p><p>In conclusion, DuckLake is an interesting attempt to simplify the modern lakehouse architecture. By reducing the number of required components and moving metadata management into a relational database, it offers a much lighter approach compared to traditional lakehouse stacks built around Iceberg, Hudi or Delta Lake.</p><p>However, the current limitation of DuckLake is not the architecture itself, but the ecosystem around it. While DuckDB already provides excellent support, wider adoption will depend on other engines and tools integrating with the format.</p><p>In its current state, it should therefore be viewed as a promising experiment rather than a production-ready replacement for existing lakehouse table formats.</p><p>As stated on the official website:</p><blockquote><a href="https://ducklake.select/faq#is-ducklake-production-ready">Is DuckLake production-ready?</a></blockquote><blockquote>While we tested DuckLake extensively, it is not yet production-ready as demonstrated by its version number 0.4. We expect DuckLake to mature over the course of 2025.</blockquote><p>DuckLake is not yet considered production-ready. The current version, 0.4, reflects that the project is still evolving. However, progress has been moving quickly. Based on announcements from the team both on Discord and during FOSDEM 2026, <a href="https://motherduck.com/blog/DuckDB-1.5-features-I-am-excited-about">the full 1.0 release is expected in April 2026</a>.</p><p>Until then, DuckLake remains a very promising experiment in rethinking how simple a lakehouse architecture can be.</p><h3><strong>Acknowledgements</strong></h3><p>Daniel Beach, whose <a href="https://github.com/danielbeach/DuckLakeonS3andPostgres">repository</a> I used as a starting point.</p><p><a href="https://www.linkedin.com/in/amitgilad/">Amit Gilad</a>, who has kindly shared with me his presentation and largely inspired this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd0a65880ce6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datamindedbe/ducklake-wants-to-fix-the-lakehouse-can-it-fd0a65880ce6">DuckLake Wants to Fix the Lakehouse. Can It?</a> was originally published in <a href="https://medium.com/datamindedbe">Dataminded</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Stability with Python: How to Catch Even the Smallest Changes]]></title>
            <link>https://medium.com/datamindedbe/data-stability-with-python-how-to-catch-even-the-smallest-changes-7b935b0c4150?source=rss-bbf30c462a1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b935b0c4150</guid>
            <category><![CDATA[hash]]></category>
            <category><![CDATA[dataframes]]></category>
            <category><![CDATA[comparison]]></category>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[pandas]]></category>
            <dc:creator><![CDATA[Grigorii Osipov]]></dc:creator>
            <pubDate>Thu, 01 Aug 2024 08:01:48 GMT</pubDate>
            <atom:updated>2024-08-01T08:20:50.011Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bWoElpSLfV6QkdeWwRyqAA.png" /><figcaption>Slight changes can mean a whole lot of resource usage</figcaption></figure><p>As a data engineer, it is nearly always the safest option to run data pipelines every X minutes. This allows you to sleep well at night, knowing you haven’t missed any updates coming from upstream.</p><p>Unfortunately, this approach doesn’t bode well when you have to account for the large load on infrastructure and the bill that comes at the end of the month. Quite often, it is only really needed to run them when there has been changes upstream. Additionally, simply re-running them means that we do not actually know when the real updates have occurred upstream. One of the ways to see if 2 files are identical is to compare their hashes, which can be done with a simple function shown below:</p><pre>import hashlib<br><br>def calculate_file_hash_chunked(file_path: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    Calculate the hash of a file using chunks<br>    Due to shorter hash and as such more readable hash, md5 is used<br><br>    :param file_path: The path to the CSV file.<br>    :return: The hash of the file as a hexadecimal string.<br>    &quot;&quot;&quot; <br>    hash_obj = hashlib.md5() <br>    with open(file_path, &#39;rb&#39;) as file:<br>        for chunk in iter(lambda: file.read(4096), b&quot;&quot;):<br>            hash_obj.update(chunk)<br>    return hash_obj.hexdigest()</pre><p>Hashes are generally an alphanumeric string, which uses a deterministic algorithm to compute a unique result of an input, which is one of the reasons it can be used. A deterministic algorithm in this context mean there is no outside inputs nor there is any randomness except for the input provided. Here you can see an example of a “shorter” MD5 hash; `938c2cc0dcc05f2b68c4287040cfcf71`.</p><p>However, we might find this approach insufficiently consistent, as we might not be aware of how the files are generated upstream. The fact that a single row being moved 1 row up/down will create a completely different hash makes it difficult to know if the data inside has changed, as what we truly want to know is if the data has changes instead of the file itself.</p><blockquote>Did the data change or are the rows simply rearranged?</blockquote><h3>Pandas</h3><p>To solve this, a simple pandas DataFrame method is usually sufficient to identify changes. If we load the data into a DataFrame, then sort the columns followed by sorting all the rows, we can confidently say that the data hasn’t changed by hashing it all together.</p><p>An important mention should be left for stability of the sort, as obtaining the same results on the run is an important feature. A stable sort is a sort that maintains the order of elements with identical values, as they were before the sort. However we work on the assumption that only the data inside the DataFrame matters and that the DataFrame might simply be rearranged, so the stability of the sort does not matter. So regardless of the stability of the sort, the fact that we sort rows one after another makes it an option that does not need to be considered.</p><pre>import pandas as pd<br>from typing import Optional<br><br>def sort_dataframe(<br>    df: pd.DataFrame,<br>    sort_rows: Optional[bool] = True,<br>    sort_columns: Optional[bool] = True,<br>) -&gt; pd.DataFrame:<br>    &quot;&quot;&quot;<br>    Sort the DataFrame by columns and/or rows based on the provided options.<br><br>    :param df: The input DataFrame.<br>    :param sort_rows: Whether to sort the rows. Default is True.<br>    :param sort_columns: Whether to sort the columns. Default is True.<br>    :return: The sorted DataFrame.<br>    &quot;&quot;&quot;<br>    if sort_columns:<br>        df = df.reindex(sorted(df.columns), axis=1)<br>    if sort_rows:<br>        df = df.sort_values(by=list(df.columns)).reset_index(drop=True)<br>    <br>    return df</pre><p>This will already allow us to easily compare two ambiguous DataFrames, as seen below:</p><pre>data1 = {<br>    &#39;A&#39;: [True, False, True],<br>    &#39;B&#39;: [1, 2, 3],<br>    &#39;C&#39;: [&#39;foo&#39;, &#39;bar&#39;, &#39;baz&#39;]<br>}<br>data2 = {<br>    &#39;C&#39;: [&#39;baz&#39;, &#39;foo&#39;, &#39;bar&#39;],<br>    &#39;B&#39;: [3, 1, 2],<br>    &#39;A&#39;: [True, True, False]<br>}<br><br>df1 = pd.DataFrame(data1)<br>df2 = pd.DataFrame(data2)<br><br>if df1.equals(df2):<br>    print(&quot;DataFrames are equal before sorting.&quot;)<br><br>df1_sorted = sort_dataframe(df1)<br>df2_sorted = sort_dataframe(df2)<br><br>print(df2_sorted)<br><br>if df1_sorted.equals(df2_sorted):<br>    print(&quot;DataFrames are equal after sorting.&quot;)<br><br>------<br>       A  B    C<br>0  False  2  bar<br>1   True  1  foo<br>2   True  3  baz<br><br>DataFrames are equal after sorting.</pre><p>As seen above, boolean values are sorted with column B being the deciding factor for which value comes first, as they hold the same value in column A.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/0*_2iSz7suCA-37kTL.gif" /><figcaption>Quicksort is used by default as pandas sorting method</figcaption></figure><h3>Hashing</h3><p>However, quite often, getting access to the previous DataFrame can be quite tedious, time-consuming, and inefficient. What makes more sense is simply hashing the DataFrame as a whole and saving the result somewhere it can be easily fetched.</p><pre>import hashlib<br>import io<br>import pandas as pd<br><br>def hash_pandas_dataframe(df: pd.DataFrame) -&gt; str:<br>    buffer = io.BytesIO()<br>    df.to_feather(buffer)<br>    buffer.seek(0)<br>    feather_bytes = buffer.read()<br>    return hashlib.md5(feather_bytes).hexdigest()</pre><p>The example above loads it directly into memory and hashes it in the Feather format, which is deterministic. If the hashes of two separate files, or in this case, DataFrames, are the same, it means that either the two files are identical or a hash collision has occurred. Given that we are trying to determine if two objects are identical, we can assume the much more likely probability ( <a href="https://www.ascii-code.com/character/%C2%B1#:~:text=Press%20%22Alt%22%20and%20type%20%22,where%20your%20cursor%20is%20placed.">±</a> 1 in 10²⁹ ) that the two datasets are identical.</p><p>This approach works for other formats such as Parquet if they are also read into Pandas, as the core processes of sorting and hashing remain the same.</p><p>Stay tuned for the next entry on hashing data files, where different ways to hash are highlighted and the superior speed of Polars is demonstrated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b935b0c4150" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datamindedbe/data-stability-with-python-how-to-catch-even-the-smallest-changes-7b935b0c4150">Data Stability with Python: How to Catch Even the Smallest Changes</a> was originally published in <a href="https://medium.com/datamindedbe">Dataminded</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>