<?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 Eric Ti Yu Chiang on Medium]]></title>
        <description><![CDATA[Stories by Eric Ti Yu Chiang on Medium]]></description>
        <link>https://medium.com/@serixscorpio?source=rss-c27392d59022------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TYHj5ZtVmhZu3hbjRoPpLg.png</url>
            <title>Stories by Eric Ti Yu Chiang on Medium</title>
            <link>https://medium.com/@serixscorpio?source=rss-c27392d59022------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 21:47:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@serixscorpio/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[__main__ — Top-level code environment]]></title>
            <link>https://medium.com/@serixscorpio/main-top-level-code-environment-7ea554258957?source=rss-c27392d59022------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ea554258957</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming-tips]]></category>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[scripting]]></category>
            <dc:creator><![CDATA[Eric Ti Yu Chiang]]></dc:creator>
            <pubDate>Fri, 03 Mar 2023 09:05:07 GMT</pubDate>
            <atom:updated>2023-03-03T09:05:07.058Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Nm8ytEuaGX20Jpm4" /><figcaption>Photo by <a href="https://unsplash.com/@dnevozhai?utm_source=medium&amp;utm_medium=referral">Denys Nevozhai</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>What does if __name__ == &#39;__main__&#39; do?</p><p>A Python <strong>module</strong> is a file containing Python definitions and statements. When a module is imported, __name__ is set to the module name:</p><pre>&gt;&gt;&gt; import os<br>&gt;&gt;&gt; os.__name__<br>&#39;os&#39;</pre><p>If the module is executed in the top-level code environment, then __name__ is set to __main__. The top-level code (also known as an <em>entry point</em>) is the first user-specified Python module to run. Consider a file helloworld.py:</p><pre>def greet():<br>    print(&quot;hello&quot;)<br>if __name__ == &#39;__main__&#39;:<br>    greet()</pre><p>The helloworld module is executed in the top-level environment when tt is passed to the Python interpreter as a file:</p><pre>$ python helloworld.py<br>hello</pre><p>or when it is passed to the Python interpreter with -m argument:</p><pre>$ python -m helloworld<br>hello</pre><p>In the wild, if __name__ == &#39;__main__&#39; can be found in a module that is intended to be run as a script. When such a module is imported from another module (say to unit test it), the script code won&#39;t accidentally run. For example, a unit test for helloworld would look like:</p><pre>from helloworld import greet<br>def test_greet():<br>    # test setup<br>    greet()<br>    # test teardown</pre><p>To summarize, code within the if __name__ == &#39;__main__&#39; block won&#39;t execute unless the module is executed in the top-level environment.</p><p>Reference: <a href="https://docs.python.org/3.11/library/__main__.html#module-__main__">Python Runtime Services — <strong>main</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ea554258957" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Domain Modeling: Business Rule Change and Discovery]]></title>
            <link>https://medium.com/@serixscorpio/domain-modeling-business-rule-change-and-discovery-b209b3a98019?source=rss-c27392d59022------2</link>
            <guid isPermaLink="false">https://medium.com/p/b209b3a98019</guid>
            <category><![CDATA[domain-model]]></category>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[domain-modeling]]></category>
            <dc:creator><![CDATA[Eric Ti Yu Chiang]]></dc:creator>
            <pubDate>Fri, 30 Dec 2022 08:46:19 GMT</pubDate>
            <atom:updated>2022-12-30T08:46:19.797Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Interior of a warehouse with multiple levels of inventory stacks" src="https://cdn-images-1.medium.com/max/1024/0*MYT9T5tOzzctwGgg" /><figcaption>Photo by <a href="https://unsplash.com/@tommaomaoer?utm_source=medium&amp;utm_medium=referral">tommao wang</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Sometimes I feel a little disoriented when navigating various topics of domain driven design, so I come back to the following definitions as a reference point:</p><ol><li>What is a domain?<br>A domain is a (business) problem area that can potentially be solved by computer software.</li><li>What is a domain model?<br>A domain model is a simplified and useful representation of the domain done in computer software.</li><li>What is domain modeling?<br>Domain modeling is an (iterative) process of building a domain model.</li><li>Why do domain modeling?<br>Domain modeling facilitates producing a software solution for a domain problem and shares domain knowledge from domain experts to software developers.</li></ol><p>To appreciate domain modeling in practice, I rely on <a href="https://www.cosmicpython.com/book/chapter_01_domain_model.html">Chapter 1: Domain Modeling</a> of Harry Percival &amp; Bob Gregory’s “Architecture Patterns with Python” free book. The chapter walks through how to come up with a domain model with no external dependencies or infrastructural concerns. Next, I’ll describe my experimentation and reflections upon reading the chapter. I recommend skimming through the chapter first to gain some context to follow my train of thought more easily. Here’s the link to the chapter again: <a href="https://www.cosmicpython.com/book/chapter_01_domain_model.html">https://www.cosmicpython.com/book/chapter_01_domain_model.html</a></p><p>The chapter starts with an introduction of a domain the authors are involved in. It’s about an online retailer of furniture, see <a href="https://www.cosmicpython.com/book/chapter_01_domain_model.html#allocation_context_diagram">context diagram</a>. Then it drills down to explore the domain language. The relevant terms are allocation, batch, and order lines. It then presents a collection of more detailed notes that serve as the starting point for domain modeling. These notes are typically taken during discussions with domain experts. An example note looks like: “When we’ve allocated an order line to a batch, we will send stock from that specific batch to the customer’s delivery address.”</p><p>In the real world, we rarely have all the necessary information upfront, nor do things remain static. What if certain key details are missing or changed during this step? How would the domain modeling pan out?</p><p>Consider this scenario: suppose it was decided to only allocate orders when real stock is available in the warehouse. Perhaps it is desirable to get the allocation system up and running quickly, so the business decides to skip treating shipments yet to arrive as real stock.</p><p>Let’s update a few unit tests to capture the essence of these business rules:</p><pre>def test_allocating_to_a_batch_reduces_the_available_quantity():<br>-   batch = Batch(&quot;batch-001&quot;, &quot;SMALL-TABLE&quot;, qty=20, eta=date.today())<br>+   batch = Batch(&quot;batch-001&quot;, &quot;SMALL-TABLE&quot;, qty=20)<br>    line = OrderLine(&quot;order-ref&quot;, &quot;SMALL-TABLE&quot;, 2)<br>batch.allocate(line)<br>assert batch.available_quantity == 18</pre><p>The testing logic for what we can allocate are slightly modified:</p><pre>def make_batch_and_line(sku, batch_qty, line_qty):<br>    return (<br>-       Batch(&quot;batch-001&quot;, sku, batch_qty, eta=date.today()),<br>+       Batch(&quot;batch-001&quot;, sku, batch_qty),<br>        OrderLine(&quot;order-123&quot;, sku, line_qty),<br>    )<br><br>def test_can_allocate_if_available_greater_than_required():<br>    large_batch, small_line = make_batch_and_line(&quot;ELEGANT-LAMP&quot;, 20, 2)<br>    assert large_batch.can_allocate(small_line)<br><br>def test_cannot_allocate_if_available_smaller_than_required():<br>    small_batch, large_line = make_batch_and_line(&quot;ELEGANT-LAMP&quot;, 2, 20)<br>    assert small_batch.can_allocate(large_line) is False<br><br>def test_can_allocate_if_available_equal_to_required():<br>    batch, line = make_batch_and_line(&quot;ELEGANT-LAMP&quot;, 2, 2)<br>    assert batch.can_allocate(line)<br><br>def test_cannot_allocate_if_skus_do_not_match():<br>-   batch = Batch(&quot;batch-001&quot;, &quot;UNCOMFORTABLE-CHAIR&quot;, 100, eta=None)<br>+   batch = Batch(&quot;batch-001&quot;, &quot;UNCOMFORTABLE-CHAIR&quot;, 100)<br>    different_sku_line = OrderLine(&quot;order-123&quot;, &quot;EXPENSIVE-TOASTER&quot;, 10)<br>    assert batch.can_allocate(different_sku_line) is False</pre><p>Some of the original test cases remain unchanged:</p><pre>def test_can_only_deallocate_allocated_lines():<br>    batch, unallocated_line = make_batch_and_line(&quot;DECORATIVE-TRINKET&quot;, 20, 2)<br>    batch.deallocate(unallocated_line)<br>    assert batch.available_quantity == 20<br><br>def test_allocation_is_idempotent():<br>    batch, line = make_batch_and_line(&quot;ANGULAR-DESK&quot;, 20, 2)<br>    batch.allocate(line)<br>    batch.allocate(line)<br>    assert batch.available_quantity == 18</pre><p>Some of the original test cases from the chapter no longer applies:</p><pre>- def test_prefers_current_stock_batches_to_shipments():<br>-     …<br> <br>- def test_prefers_earlier_batches():<br>-     …</pre><p>The test for the allocate domain service function needs to be updated as well:</p><pre>def test_returns_allocated_batch_ref():<br>-   in_stock_batch = Batch(&quot;in-stock-batch-ref&quot;, &quot;HIGHBROW-POSTER&quot;, 100, eta=None)<br>-   shipment_batch = Batch(&quot;shipment-batch-ref&quot;, &quot;HIGHBROW-POSTER&quot;, 100, eta=tomorrow)<br>+   first_batch = Batch(&quot;batch-ref-1&quot;, &quot;HIGHBROW-POSTER&quot;, 100)<br>+   second_batch = Batch(&quot;batch-ref-2&quot;, &quot;HIGHBROW-POSTER&quot;, 100)<br><br>    line = OrderLine(&quot;oref&quot;, &quot;HIGHBROW-POSTER&quot;, 10)<br>-   allocation = allocate(line, [in_stock_batch, shipment_batch])<br>+   allocation = allocate(line, [first_batch, second_batch])<br>    assert allocation == in_stock_batch.reference</pre><p>Since allocate no longer need batches to be sorted by eta, the concept of ordering batches goes away:</p><pre>class Batch:<br>     ...<br><br>-    def __gt__(self, other):<br>-        if self.eta is None:<br>-            return False<br>-        if other.eta is None:<br>-            return True<br>-        return self.eta &gt; other.eta<br><br>...<br><br>def allocate(line: OrderLine, batches: List[Batch]) -&gt; str:<br>-    batch = next(b for b in sorted(batches) if b.can_allocate(line))<br>+    batch = next(b for b in batches if b.can_allocate(line))<br>    batch.allocate(line)<br>    return batch.reference</pre><p>Testing out-of-stock exception becomes:</p><pre>def test_raises_out_of_stock_exception_if_cannot_allocate():<br>-    batch = Batch(&quot;batch1&quot;, &quot;SMALL-FORK&quot;, 10, eta=today)<br>+    batch = Batch(&quot;batch1&quot;, &quot;SMALL-FORK&quot;, 10)<br>    allocate(OrderLine(&quot;order1&quot;, &quot;SMALL-FORK&quot;, 10), [batch])<br><br>    with pytest.raises(OutOfStock, match=&quot;SMALL-FORK&quot;):<br>        allocate(OrderLine(&quot;order2&quot;, &quot;SMALL-FORK&quot;, 1), [batch])</pre><p>Overall, the resulting interactions between Batch (an entity), OrderLine (a value object) and allocate (a domain service function) seem largely similar to the original implementation from the Book. In this experiment, changing business rule led to changing unit tests, which resulted in changing the domain model. Fortunately, the changes mostly apply to the leaf attribute (eta) of an entity (Batch), so they are relatively simple and avoid ripple effects.</p><p>Zooming back out, I noticed there is one part that feels somewhat magical to me. It’s the process of turning business rules into unit tests. So far, I can think of a couple of heuristics to facilitate surfacing relevant unit tests:</p><p>1. Additional checks involving identity, equality and/or hashability may be worthwhile to flesh out. For example, can a Batch be uniquely identified? If so, how to uniquely identify a Batch?<br>2. Can a behavior happen in reverse or happen in multiple modes? For example, since we have allocate, would deallocate make sense to model?<br>3. Can a behavior be broken down into smaller steps? For example, aside from available_quantity being reduced, should something else happen as part of allocate?<br>4. Is there some environmental context that would affect certain behaviors? For example, can allocate happen anytime of day? Can allocate change based on the locale?</p><p>The heuristics are somewhat derived from tactical domain driven design ideas like value objects, entities, and domain service functions. I have a hunch these heuristics can be improved and organized further. If you want to go deeper, I recommend a podcast episode: <a href="https://ericnormand.me/podcast/layout-of-domain-modeling-book">Layout of Domain Modeling book</a> by Eric Normand (author of “Grokking Simplicity”).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b209b3a98019" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Mocks: Where to Patch]]></title>
            <link>https://medium.com/@serixscorpio/python-mocks-where-to-patch-7b2388af4f0b?source=rss-c27392d59022------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b2388af4f0b</guid>
            <category><![CDATA[mock]]></category>
            <category><![CDATA[mocking]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pytest]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Eric Ti Yu Chiang]]></dc:creator>
            <pubDate>Fri, 16 Dec 2022 01:06:50 GMT</pubDate>
            <atom:updated>2022-12-16T01:06:50.815Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A metal key half buried on a forest floor." src="https://cdn-images-1.medium.com/max/1024/0*h7txFXRwjqWQlpS7" /><figcaption>Photo by <a href="https://unsplash.com/@lazycreekimages?utm_source=medium&amp;utm_medium=referral">Michael Dziedzic</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I have been bitten by where to patch when using python mocks many times. So this is for my future self and for others who find themselves in this rough patch (pun intended).</p><p>The following example makes use of <a href="https://docs.pytest.org/en/7.2.x/">pytest</a>, and <a href="https://pytest-mock.readthedocs.io/en/latest/">pytest-mock</a>. The code can be found at: <a href="https://github.com/serixscorpio/writing-companion-code/tree/main/python-mocks-where-to-patch">https://github.com/serixscorpio/writing-companion-code/tree/main/python-mocks-where-to-patch</a>.</p><p>I have a function named offset. It is slow because it depends on expensive_calculation:</p><pre>“””File: client1.py”””<br>from api import expensive_calculation<br><br>def offset(amount):<br> result = expensive_calculation()<br> return result + amount</pre><p>Function expensive_calculation takes 5 seconds to run:</p><pre>“””File: api.py”””<br>import time<br><br>def expensive_calculation():<br> time.sleep(5)<br> return 10</pre><p>When testing offset, we only care about the result from expensive_calculation, so let’s mock expensive_calculation to speed up the test:</p><pre>&quot;&quot;&quot;File: test_clients.py&quot;&quot;&quot;<br>import client1<br><br>def test_client1_offset(mocker):<br> mocker.patch.object(client1, &quot;expensive_calculation&quot;, return_value=20)<br> assert client1.offset(1) == 21</pre><p>Since client1 already has a reference to expensive_calculation (the real, slow implementation) we patch expensive_calculation on client1, not on api. Patching expensive_calculation on api will have no effect on our test. See <a href="https://docs.python.org/3/library/unittest.mock.html#where-to-patch">official documentation</a> on this.</p><p>Consider an alternate import approach when implementing offset. Instead of from api import expensive_calculation, we use import api and api.expensive_calculation:</p><pre>&quot;&quot;&quot;File: client2.py&quot;&quot;&quot;<br>import api<br><br>def offset(amount):<br> result = api.expensive_calculation()<br> return result + amount</pre><p>The key difference is module client2 does not have a reference to expensive_calculation directly. Only api does. We modify the test to patch expensive_calculation on api :</p><pre>&quot;&quot;&quot;File: test_clients.py&quot;&quot;&quot;<br>import api<br>import client2<br><br>def test_client2_offset(mocker):<br> mocker.patch.object(api, &quot;expensive_calculation&quot;, return_value=20)<br> assert client2.offset(1) == 21</pre><p>Both import approaches are common. Hopefully this illustrates where to patch depends on where the function is looked up.</p><h4>Reference</h4><ol><li>Official documentation on <a href="https://docs.python.org/3/library/unittest.mock.html#where-to-patch">patch()</a>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b2388af4f0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>