<?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 Snir Orlanczyk on Medium]]></title>
        <description><![CDATA[Stories by Snir Orlanczyk on Medium]]></description>
        <link>https://medium.com/@snir-orlanczyk?source=rss-d258e3808bbf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*L5TX6vxW3rrDXSGT0BAz5w.jpeg</url>
            <title>Stories by Snir Orlanczyk on Medium</title>
            <link>https://medium.com/@snir-orlanczyk?source=rss-d258e3808bbf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:40:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@snir-orlanczyk/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[AsyncGenerators with chain execution]]></title>
            <link>https://snir-orlanczyk.medium.com/asyncgenerators-with-chain-execution-b772c148f9dd?source=rss-d258e3808bbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/b772c148f9dd</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Snir Orlanczyk]]></dc:creator>
            <pubDate>Mon, 24 Feb 2025 02:39:32 GMT</pubDate>
            <atom:updated>2025-02-24T15:57:47.471Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iwn4XKp0aRJT94YqysGK6g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@kar111?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Karine Avetisyan</a> on <a href="https://unsplash.com/photos/brown-metal-chain-with-white-background-ipuiM-36tAg?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>With the rise of LLMs the need to stream data to the client is becoming more and more common.</p><p>What if we wanted to capture metadata on the stream?</p><p>What if we wanted to modify the content of the stream?</p><p>A common why to do it is with a message queue, but what if we want to keep it simpler without another piece of infrastructure.Instead we can use a chain of handlers to handle both usecases.</p><h3>Let’s check it out</h3><p>A simple way to achieve it would be to use a version of the chain pattern combined with a builder.</p><pre>import asyncio<br>from typing import AsyncGenerator, Callable, List, Any, Awaitable<br><br><br>class StreamProxy:<br>    &quot;&quot;&quot;<br>    A proxy for an async generator stream that allows handlers to modify or inspect chunks in a chain<br>    &quot;&quot;&quot;<br><br>    def __init__(self):<br>        self.handlers: List[Callable[[Any], Awaitable[Any]]] = []<br><br>    def add_handler(self, handler: Callable[[Any], Awaitable[Any]]) -&gt; &#39;StreamProxy&#39;:<br>        &quot;&quot;&quot;<br>        Add a handler to the chain.<br><br>        Args:<br>            handler: A callable that receives a chunk, and returns the modified chunk.<br>        &quot;&quot;&quot;<br>        self.handlers.append(handler)<br>        return self<br><br>    async def process_chunk(self, chunk: Any) -&gt; Any:<br>        &quot;&quot;&quot;<br>        Process a single chunk through the chain of handlers.<br><br>        Args:<br>            chunk: The chunk to process.<br><br>        Returns:<br>            The modified chunk.<br>        &quot;&quot;&quot;<br>        for handler in self.handlers:<br>            chunk = await handler(chunk)<br>        return chunk<br><br>    async def proxy(self, stream: AsyncGenerator[Any, None]) -&gt; AsyncGenerator[Any, None]:<br>        &quot;&quot;&quot;<br>        Proxy the stream and apply handlers to each chunk.<br><br>        Args:<br>            stream: The async generator stream to proxy.<br><br>        Yields:<br>            The modified chunks from the stream.<br>        &quot;&quot;&quot;<br>        async for chunk in stream:<br>            yield await self.process_chunk(chunk)<br><br><br># Example usage<br>async def uppercase_handler(chunk: str) -&gt; str:<br>    return chunk.upper()<br><br><br>async def add_prefix_handler(chunk: str) -&gt; str:<br>    return f&quot;Modified: {chunk}&quot;<br><br><br># Example async generator stream<br>async def example_stream() -&gt; AsyncGenerator[str, None]:<br>    for item in [&quot;hello&quot;, &quot;world&quot;, &quot;stream&quot;]:<br>        await asyncio.sleep(0.1)  # Simulate async work<br>        yield item<br><br><br>async def main():<br>    proxy = StreamProxy() \<br>        .add_handler(uppercase_handler) \<br>        .add_handler(add_prefix_handler)<br><br>    # Proxy the stream and print modified chunks<br>    async for modified_chunk in proxy.proxy(example_stream()):<br>        print(modified_chunk)<br><br><br># Run the example<br>asyncio.run(main())</pre><p>The examples define 2 handlers one that changes the text to upper case and another that adds a prefix to it. they receive each yielded text in order and modify it until the array reached its end</p><p>The input here will be an array of hello, world, stream and with the modifiers the output will be Modified: HELLO, Modified: WORLD, Modified: STREAM.</p><h3>Let’s take it once step further</h3><p>A common need would be to share context between the handlers, and a great solution here would be to use context vars, would look like so</p><pre>import asyncio<br>from typing import AsyncGenerator, Callable, List, Any, Awaitable<br>from contextvars import ContextVar<br><br>stream_context = ContextVar(&quot;stream_context&quot;, default={})<br><br><br>class StreamProxy:<br>    &quot;&quot;&quot;<br>    A proxy for an async generator stream that allows handlers to modify or inspect chunks in a chain<br>    &quot;&quot;&quot;<br><br>    def __init__(self):<br>        self.handlers: List[Callable[[Any], Awaitable[Any]]] = []<br>        stream_context.set({})<br><br>    def add_handler(self, handler: Callable[[Any], Awaitable[Any]]) -&gt; &#39;StreamProxy&#39;:<br>        &quot;&quot;&quot;<br>        Add a handler to the chain.<br><br>        Args:<br>            handler: A callable that receives a chunk, and returns the modified chunk.<br>        &quot;&quot;&quot;<br>        self.handlers.append(handler)<br>        return self<br><br>    async def process_chunk(self, chunk: Any) -&gt; Any:<br>        &quot;&quot;&quot;<br>        Process a single chunk through the chain of handlers.<br><br>        Args:<br>            chunk: The chunk to process.<br><br>        Returns:<br>            The modified chunk.<br>        &quot;&quot;&quot;<br>        for handler in self.handlers:<br>            chunk = await handler(chunk)<br>        return chunk<br><br>    async def proxy(self, stream: AsyncGenerator[Any, None]) -&gt; AsyncGenerator[Any, None]:<br>        &quot;&quot;&quot;<br>        Proxy the stream and apply handlers to each chunk.<br><br>        Args:<br>            stream: The async generator stream to proxy.<br><br>        Yields:<br>            The modified chunks from the stream.<br>        &quot;&quot;&quot;<br>        async for chunk in stream:<br>            yield await self.process_chunk(chunk)<br><br><br># Example usage<br>async def uppercase_handler(chunk: str) -&gt; str:<br>    # Example: Increment a counter in the context<br>    context = stream_context.get()<br>    context[&quot;processed_chunks&quot;] = context.get(&quot;processed_chunks&quot;, 0) + 1<br>    stream_context.set(context)<br>    return chunk.upper()<br><br><br>async def add_prefix_handler(chunk: str) -&gt; str:<br>    # Example: Add metadata to the context<br>    context = stream_context.get()<br>    context[&quot;last_chunk&quot;] = chunk<br>    stream_context.set(context)<br>    return f&quot;Modified: {chunk}&quot;<br><br><br># Example async generator stream<br>async def example_stream() -&gt; AsyncGenerator[str, None]:<br>    for item in [&quot;hello&quot;, &quot;world&quot;, &quot;stream&quot;]:<br>        await asyncio.sleep(0.1)  # Simulate async work<br>        yield item<br><br><br>async def main():<br>    proxy = StreamProxy() \<br>        .add_handler(uppercase_handler) \<br>        .add_handler(add_prefix_handler)<br><br>    # Proxy the stream and print modified chunks<br>    async for modified_chunk in proxy.proxy(example_stream()):<br>        print(modified_chunk)<br><br>    # Access the shared context after processing<br>    print(&quot;Shared Context:&quot;, stream_context.get())<br><br><br># Run the example<br>asyncio.run(main())</pre><p>In this example i added a context var that can be used to capture general metadata about the steam and also to have a common state to be shared between the streams if needed.</p><h3>Real world example</h3><p>We are streaming from OpenAI and want to modify the content of the stream + capture the full text that is being streamed</p><pre>import openai<br><br>async def capture_text_handler(chunk: openai.types.chat.ChatCompletionChunk) -&gt; openai.types.chat.ChatCompletionChunk:<br>    if chunk and chunk.choices and chunk.choices[0] and chunk.choices[0].delta.content:<br>        context = stream_context.get()<br>        context[&quot;full_text&quot;] = context.get(&quot;full_text&quot;, &quot;&quot;) + chunk.choices[0].delta.content<br>        stream_context.set(context)<br>        return chunk<br>    return chunk<br><br><br>async def uppercase_handler(chunk: openai.types.chat.ChatCompletionChunk) -&gt; openai.types.chat.ChatCompletionChunk:<br>    if chunk and chunk.choices and chunk.choices[0] and chunk.choices[0].delta.content:<br>        chunk.choices[0].delta.content = chunk.choices[0].delta.content.upper()<br>        return chunk<br>    return chunk<br><br><br>async def get_openai_stream(prompt: str) -&gt; AsyncGenerator[openai.types.chat.ChatCompletionChunk, None]:<br>    client = openai.AsyncOpenAI()<br><br>    response = await client.chat.completions.create(<br>        messages=[<br>            {<br>                &quot;role&quot;: &quot;user&quot;,<br>                &quot;content&quot;: prompt,<br>            }<br>        ],<br>        model=&quot;gpt-4o&quot;,<br>        stream=True<br>    )<br><br>    async for chunk in response:<br>        yield chunk<br><br><br>async def main():<br>    # Create a proxy and add handlers<br>    proxy = StreamProxy() \<br>        .add_handler(capture_text_handler) \<br>        .add_handler(uppercase_handler)<br><br>    # Example prompt for OpenAI<br>    prompt = &quot;Count to 3 in english&quot;<br><br>    # Proxy the OpenAI response stream and print modified chunks<br>    async for modified_chunk in proxy.proxy(get_openai_stream(prompt)):<br>        if modified_chunk and modified_chunk.choices and modified_chunk.choices[0].delta.content:<br>            print(modified_chunk.choices[0].delta.content)<br><br>    # Access the shared context after processing<br>    print(&quot;Shared Context:&quot;, stream_context.get())<br><br># Run the example<br>asyncio.run(main())<br><br># Output:<br># ONE<br># ,<br>#  TWO<br># ,<br>#  THREE<br># .<br># Shared Context: {&#39;full_text&#39;: &#39;One, two, three.&#39;}</pre><h3>Conclusion</h3><p>This pattern provides an elegant and powerful way to handle data streams with ease while keep the code testable and modular.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b772c148f9dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python — Common pitfalls (and how to avoid them!)]]></title>
            <link>https://python.plainenglish.io/python-common-pitfalls-and-how-to-avoid-them-c61e0d9ea0ec?source=rss-d258e3808bbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/c61e0d9ea0ec</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Snir Orlanczyk]]></dc:creator>
            <pubDate>Mon, 12 Aug 2024 16:36:06 GMT</pubDate>
            <atom:updated>2024-08-15T16:32:41.319Z</atom:updated>
            <content:encoded><![CDATA[<h3>Python — Common pitfalls (and how to avoid them)</h3><p>I have been developing in Swift for a while and had to learn python for a backend project I was working on, during the time I was working on the project I decided to list all the potential pitfalls and weirdness that I found and write it here so that you, the reader, will be aware of them and might avoid them.</p><h3>1. Python’s pass by ref? value? by sharing.</h3><p>Python use’s a technique called <a href="https://medium.com/techtofreedom/python-is-neither-call-by-value-nor-call-by-reference-2a0c8f6f4a8f">pass by sharing </a>it is a hybrid between pass by value and reference.</p><p>Non-mutable objects (string, int, bool, float, tuple, frozenset) are effectively passed by value, under the hood it is being passed by reference into a local variable with <a href="https://en.wikipedia.org/wiki/Copy-on-write">copy on write</a> (Creates a new object locally if you try to write, but otherwise points to passed object) which isolates the caller from changes to the value, effectively making it pass by value.</p><p>Mutable objects (lists, dictionaries, set) on the other hand, act as pass by reference since they are mutable in memory, that means you need to be extra careful when passing mutable objects and manipulating them, since it can effect the original object being passed.</p><p><strong>Examples:</strong></p><p>Since mutable objects are being passed by reference, changes to the values will effect the original object from the caller.</p><pre>def something(numbers):<br>    numbers.append(5)<br><br><br>numbers = [1, 2, 3, 4]<br>print(numbers)<br>something(numbers=numbers)<br>print(numbers)<br><br># Output:<br>[1, 2, 3, 4]<br>[1, 2, 3, 4, 5]</pre><p><strong>How to avoid:</strong></p><p><a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions">List comprehension</a> and <a href="https://martinxpn.medium.com/higher-order-functions-in-python-33-100-days-of-python-7bfd66d516d8">higher order functions</a> in python can help manage mutable objects better since they create a new object from the original object.</p><pre>original_list = [1, 2, 3]<br>new_list = [x * 2 for x in original_list]<br># new_list is a new object<br><br>original_dict = {&#39;a&#39;: 1, &#39;b&#39;: 2}<br>new_dict = {k: v * 2 for k, v in original_dict.items()}<br># new_dict is a new object<br><br>original_list = [1, 2, 3]<br>new_list = list(map(lambda x: x * 2, original_list))<br># new_list is a new object<br><br>original_list = [1, 2, 3]<br>new_list = original_list.copy()<br># new_list is a new object</pre><h3>2. Mutable default arguments</h3><p>This is by far the most common unknown (and unintuitive) common pitfall.</p><p>When initiating a function with a default variable, the default value for a function argument is <strong>only evaluated once</strong>, at the time that the function is defined.</p><p>That means that <strong>when passing a mutable object</strong> (lists or dictionaries) as default arguments to a function, we will <strong>use the same object every time the function is called</strong> (assuming no value was provided and we are using the default value)</p><p><strong>Example</strong>:</p><pre>def append_to_list(value, my_list=[]):<br>    my_list.append(value)<br>    return my_list<br><br>append_to_list(5)<br># [5]<br>append_to_list(7)<br># [5,7]<br>append_to_list(2)<br># [5,7,2]</pre><p><strong>How to avoid:</strong></p><p>A common way to avoid this scenario is setting the default to null and adding a guard check that initializes a default.</p><pre>def append_to_list(value, my_list=None):<br>    if my_list is None:<br>      my_list = []<br>    my_list.append(value)<br>    return my_list<br><br>append_to_list(5)<br># [5]<br>append_to_list(7)<br># [7]<br>append_to_list(2)<br># [2]</pre><h3>3. Python scope rules</h3><p>Python scope are basically namespace rules about how object &lt;-&gt; name mapping is done, it is called <a href="https://www.geeksforgeeks.org/scope-resolution-in-python-legb-rule/">LEGB</a> and it stand for local, enclosed, global, built in. These scopes are evaluated in the specified order.</p><h4>Shadowing lower scopes</h4><p>In Python, shadowing occurs when a variable declared within a certain scope (like a function or a class) has the same name as a variable declared in an outer scope. This means the inner variable “shadows” the outer variable, making the outer variable inaccessible within the inner scope.</p><p><strong>Examples:</strong></p><p>Example 1 — global scope variable— reading (works)</p><pre>x = 10  # Global variable<br><br>def my_function():<br>    x = 5  # Local variable shadows the global variable<br>    print(x)  # Prints 5<br><br>my_function()<br>print(x)  # Prints 10<br><br>&quot;&quot;&quot;<br>-&gt; The global variable x is set to 10.<br>-&gt; Inside my_function, a local variable x is created and set to 5, shadowing the global x.<br>-&gt; When print(x) is called inside the function, it prints the local x (5).<br>-&gt; Outside the function, the global x remains unchanged and prints 10.<br>&quot;&quot;&quot;<br></pre><p>Example 2— global scope variable — mutating (fails)</p><pre>x = 10  # Global variable<br><br>def my_function():<br>    x += 5  # Attempt to modify the global variable<br>    print(x)<br><br>my_function()<br>print(x)<br><br>&quot;&quot;&quot;<br>UnboundLocalError: local variable &#39;x&#39; referenced before assignment<br>&quot;&quot;&quot;</pre><p><strong>Why does this example fails?</strong></p><ul><li>This error occurs because Python treats x += 5 as an attempt to modify a local variable x. However, since x is not defined within the local scope of my_function, Python raises an UnboundLocalError.</li><li>In example 1, x = 5 creates a new local variable x within the function, shadowing the global x.</li><li>In example 2, x += 5 tries to modify x in place. Python assumes x is a local variable because of the assignment operation, but since x hasn’t been defined locally, it raises an error.</li></ul><p><strong>Common ways to avoid:</strong></p><ul><li>Passing the variable as an argument — usually the best option, it explicitly defines the local variable and does not touch the global state.</li></ul><pre>x = 10  # Global variable<br><br>def my_function(x):<br>    x += 5  # Modify the local copy of the variable<br>    print(x)  # Prints 15<br>    return x<br><br>x = my_function(x)<br>print(x)  # Prints 15</pre><ul><li>Using global keyword — if you want to modify the global variable x inside the function, you can use the global keyword to explicitly declare that x refers to the global variable.</li></ul><pre>x = 10  # Global variable<br><br>def my_function():<br>    global x<br>    x += 5  # Modify the global variable<br>    print(x)  # Prints 15<br><br>my_function()<br>print(x)  # Prints 15</pre><ul><li>Using mutable data type — When you use a mutable data type, Python doesn’t create a new local variable, instead, it modifies the existing object, which is why the changes are reflected globally. (whereas changes to immutable variables creates a new local variable)</li></ul><pre>x = [10]  # Global variable as a list<br><br>def my_function():<br>    x[0] += 5  # Modify the first element of the list<br>    print(x[0])  # Prints 15<br><br>my_function()<br>print(x[0])  # Prints 15</pre><p><strong>Additional Examples:</strong></p><p>Shadowing in Built-in Functions</p><pre>def my_function():<br>    list = [1, 2, 3]  # Local variable shadows the built-in function &#39;list&#39;<br>    print(list)  # Prints [1, 2, 3]<br><br>my_function()<br>print(list)  # Raises an error because &#39;list&#39; is not defined globally<br><br>&quot;&quot;&quot;<br>-&gt; Inside my_function, the local variable list shadows the built-in list function.<br>-&gt; When print(list) is called inside the function, it prints the local variable [1, 2, 3].<br>-&gt; Outside the function, trying to print list raises an error because list is not defined globally.<br>&quot;&quot;&quot;<br></pre><p>Shadowing in Nested Functions</p><pre>def outer_function():<br>    x = 10  # Variable in the outer function<br><br>    def inner_function():<br>        x = 5  # Local variable shadows the outer function&#39;s variable<br>        print(x)  # Prints 5<br><br>    inner_function()<br>    print(x)  # Prints 10<br><br>outer_function()<br><br>&quot;&quot;&quot;<br>-&gt; The outer function outer_function has a variable x set to 10.<br>-&gt; The inner function inner_function has a local variable x set to 5, shadowing the outer function’s x.<br>-&gt; When print(x) is called inside inner_function, it prints the local x (5).<br>-&gt; When print(x) is called inside outer_function, it prints the outer function’s x (10).<br>&quot;&quot;&quot;<br></pre><h3>4. Loop variables in Lambdas</h3><p>This one is a bit weird and almost feels like a bug in python, but it is not once you understand how loop variables work in lambdas.</p><pre>funcs = [lambda x: x + i for i in range(3)]<br>print([f(0) for f in funcs])  <br># Output: [2, 2, 2]<br># Expected output: [0, 1, 2]</pre><p><strong>Why does this happen?</strong></p><p>TL;DR — The lambdas are <strong>not</strong> executed as they are created in the loop; they are only defined. The execution happens later, and by that time, the loop variable i has reached its final value. Since all lambdas share the same reference to i, they all use this final value (2) when executed.</p><p>Lets break down what is going on here</p><ul><li><strong>Lambda Definition</strong>: Each time through the loop, a <strong>new lambda function is created</strong>. The lambda captures references to the variables that it uses (like the loop variable i), but <strong>it does not execute or evaluate those variables yet.</strong></li><li><strong>Variable Reference</strong>: The lambda <strong>does not capture the value of the variable at that moment</strong>. Instead, it captures a reference to the variable itself. This means that <strong>all the lambdas created in the loop will share this reference.</strong></li><li><strong>Loop Continues</strong>: The loop continues, and the value of i changes with each iteration. Since <strong>all the lambdas share the same reference to </strong><strong>i</strong>, they will all see whatever the current value of i is when they are eventually called. <strong>Once the loop finishes, the variable </strong><strong>i will have its final value</strong> (e.g., 2 if the loop was for i in range(3)), and this is the value that all the lambda functions will use when they are later called.</li><li><strong>Execution of Lambdas</strong>: When you <strong>eventually call these lambda functions, they will all use the final value of </strong><strong>i</strong> because that&#39;s what the variable reference points to at that time.</li></ul><p><strong>How to avoid:</strong></p><p>Here, i=i creates a default argument for i that captures its current value at the time of lambda creation. Now, each lambda has its own captured value of i, and when executed, they will produce [0, 1, 2] as expected.</p><pre>funcs = [lambda x, i=i: x + i for i in range(3)]<br>print([f(0) for f in funcs])  <br># Output: [0, 1, 2]</pre><h3>5. Modifying list while iterating it</h3><p>This one may seem a bit obvious and not just a python thing, but I feel like it is worth mentioning.</p><p>Issues that can be caused by modifying a list while iterating it are:</p><p><strong>Skipping elements — </strong>When you remove an element from the list, the indices of subsequent elements are shifted. This can cause the loop to skip elements.</p><pre>my_list = [1, 2, 3, 4, 5]<br>for i in my_list:<br>    if i % 2 == 0:<br>        my_list.remove(i)<br>print(my_list)  # Output: [1, 3, 5]</pre><p><strong>Index Errors — </strong>Adding or removing elements can lead to IndexError if the loop tries to access an index that no longer exists.</p><pre>my_list = [1, 2, 3]<br>for i in range(len(my_list)):<br>    if my_list[i] == 2:<br>        my_list.append(4)<br>print(my_list)  # Output: [1, 2, 3, 4, 4]</pre><p><strong>Infinite loops — </strong>Modifying the list in a way that affects the loop condition can lead to infinite loops.</p><pre>my_list = [1, 2, 3]<br>for i in my_list:<br>    my_list.append(i)<br># This will create an infinite loop</pre><p><strong>How to avoid:</strong></p><ul><li><strong>Iterate Over a Copy</strong> — Iterate over a copy of the list to avoid modifying the list you’re iterating over.</li></ul><pre>my_list = [1, 2, 3, 4, 5]<br>for i in my_list[:]:<br>    if i % 2 == 0:<br>        my_list.remove(i)<br>print(my_list)  # Output: [1, 3, 5]</pre><ul><li><strong>Use List Comprehensions</strong> — Based on the same principal as before, using list Comprehensions create a new list, which helps avoid modifying the original list, plus in some cases might be a clener way to do things.</li></ul><pre>my_list = [1, 2, 3, 4, 5]<br>my_list = [i for i in my_list if i % 2 != 0]<br>print(my_list)  # Output: [1, 3, 5]</pre><h4>General Best Practices</h4><ul><li><strong>Avoid in-place modifications</strong>: Whenever possible, avoid modifying the list in place during iteration. Use list comprehensions, filters, or create new lists instead.</li><li><strong>Use list methods wisely</strong>: When removing elements, consider using methods like filter(), which returns a new list, or list.pop() in reverse iteration.</li><li><strong>Consider other data structures</strong>: If frequent modifications during iteration are necessary, consider using other data structures (like deque from the collections module).</li></ul><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c61e0d9ea0ec" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/python-common-pitfalls-and-how-to-avoid-them-c61e0d9ea0ec">Python — Common pitfalls (and how to avoid them!)</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python async context — The basics]]></title>
            <link>https://snir-orlanczyk.medium.com/python-async-context-the-basics-3b770ac2d083?source=rss-d258e3808bbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b770ac2d083</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Snir Orlanczyk]]></dc:creator>
            <pubDate>Sun, 28 Jul 2024 16:14:37 GMT</pubDate>
            <atom:updated>2024-07-30T20:20:56.061Z</atom:updated>
            <content:encoded><![CDATA[<h3>Python async context — The basics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5wiHIS6Vt5ZefvWrLrHe-g.jpeg" /></figure><h3>Prerequisites</h3><p>To understand what is context and why we need it, we first need to discuss the basics of async programming in python.</p><p>To keep it simple lets discuss to main terms of the async programming: Event loop, Tasks</p><h4>Event loop</h4><p>The event loop is a core component responsible for executing asynchronous tasks. It acts as the central mechanism that schedules and runs coroutines, manages I/O operations, and handles events in an asynchronous program, It keeps running until all tasks are finished or you explicitly stop it.</p><h4>Task</h4><p>To discuss a task we need to mention 2 terms first:</p><ul><li>Coroutine — The base for async programming, this is a function that can be paused and resume, doing so allows the call to be non-blocking and for the execution of this call to continue and resume.</li><li>Future — An object used to represent the result of an asynchronous computation or operation.</li></ul><p>An asyncio Task is a subclass of Future which wraps around a coroutine and schedules it to be run by the event loop.</p><p>A Task allows you to manage and run multiple coroutines concurrently, The event loop executes these tasks and handles their completion, and it will also manage the lifecycle statue of the coroutine (Tasks have a lifecycle that includes states such as pending, running, and finished)</p><h3>Context</h3><h4>What is it?</h4><p>Context variables are similar to <a href="https://en.wikipedia.org/wiki/Thread-local_storage">thread-local storage</a> but work within the context of asynchronous tasks and coroutines, They allow you to store small pieces of data that is available to an async task throughout the task execution, and is isolated from other tasks.</p><p>A context represents a snapshot of the context variables at a given point in time. Each asynchronous task or coroutine operates within a context, and contexts are preserved when tasks are switched.</p><p>Contexts are managed by the event loop. When a coroutine or task is switched, the context is saved and restored appropriately, ensuring that context variables maintain their values across asynchronous boundaries.</p><p>A context will be created an associated with each task, and will be propagated to child tasks that are created from the task.</p><h4>Why do we need it?</h4><p>Since the execution of tasks is being paused and resumed, we can’t really use global variables to capture and maintain global states of a task(since changing a global state will leak into other tasks) and that is where context variables come into play, They can help us maintain an isolated execution state, meaning we can persist task specific information between tasks switching while keeping it isolated from other tasks.</p><h4>Use cases</h4><p>Classic use cases for using context are:</p><ul><li>Logging — We can use context to capture data that we want to log throughout an execution of a task</li><li>Feature flags — We can persist the state of a flag throughout the task execution.</li><li>User sessions and configurations — persisting user sessions and configuration data through a task execution.</li></ul><h4>How to use it</h4><p><strong>Basic</strong></p><ul><li>This is how to set and read a context variable, as you can see we are not passing the user id explicitly to the function and it is able to read it from context.</li></ul><pre>import contextvars<br>import asyncio<br><br># Create a context variable for user ID<br>user_id_var = contextvars.ContextVar(&#39;user_id&#39;)<br><br>async def perform_action():<br>    user_id = user_id_var.get()<br>    # Perform action based on user ID<br>    print(f&quot;Action performed for user ID: {user_id}&quot;)<br><br>user_id_var.set(&quot;user-123&quot;)<br>asyncio.run(perform_action)<br>#output: Action performed for user ID: user-123</pre><p><strong>Advanced</strong></p><ul><li>a more advance use case is when we want to capture more complex object than string (like a data class or a dictionary)</li><li>It is a best practice to create a getter method for the context and restrict direct access to the context, it provides for a cleaner and more flexible interface, and prevents accidental write access which can create inconsistencies.</li></ul><pre>import asyncio<br>import contextvars<br>from pydantic import BaseModel<br><br># Define the Pydantic model<br>class UserModel(BaseModel):<br>    user_id: int<br>    username: str<br><br># Create a context variable<br>user_model_var[UserModel] = contextvars.ContextVar(&#39;user_model&#39;)<br><br>async def set_user_model(user_model: UserModel):<br>    # Set the Pydantic model in the context variable<br>    user_model_var.set(user_model)<br><br>async def get_user_model() -&gt; UserModel:<br>    # Access the Pydantic model from the context variable<br>    user_model = user_model_var.get()<br>    print(f&#39;User ID: {user_model.user_id}, Username: {user_model.username}&#39;)<br><br>async def main():<br>    # Create an instance of UserModel<br>    user_model = UserModel(user_id=1, username=&#39;john_doe&#39;)<br>    <br>    # Run asynchronous tasks<br>    await set_user_model(user_model)<br>    user = await get_user_model()<br>    print(&quot;username is: {user.username}&quot;)<br><br># Run the event loop<br>asyncio.run(main())</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b770ac2d083" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FastApi background tasks — but better.]]></title>
            <link>https://snir-orlanczyk.medium.com/fastapi-background-tasks-c206312a6f56?source=rss-d258e3808bbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/c206312a6f56</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[asyncio]]></category>
            <dc:creator><![CDATA[Snir Orlanczyk]]></dc:creator>
            <pubDate>Sun, 18 Feb 2024 15:38:49 GMT</pubDate>
            <atom:updated>2024-02-18T22:54:31.430Z</atom:updated>
            <content:encoded><![CDATA[<p>Say you’re running a FastApi service and you want to trigger a long running task that you don’t want to wait for, a common use case for it is analytics, you just want to fire and forget it.</p><p>One way to solve it is to use <a href="https://fastapi.tiangolo.com/tutorial/background-tasks/">FastApi background tasks</a>, but those are very limiting they force you to start a background task at the router level, which means your whole flow is going to run as a background task, that won’t work.</p><p>Now depends on what you’re trying to run and your use case there a couple more options</p><ol><li>For synchronous IO blocking — schedule it on a thread with asyncio <a href="https://docs.python.org/3/library/asyncio-task.html#asyncio.to_thread">to_thread</a> or use a library like <a href="https://github.com/miguelgrinberg/greenletio">greenletio</a> which can do it for you but on a thread.</li><li>For async calls — you can either send the coroutine to your existing FastApi loop or start another thread with another loop and submit your coroutine there.</li></ol><h3>1. Synchronous blocking calls</h3><p>The use case here is when running an async app and you have a IO blocking calls or a CPU heavy call and you want to run it in a thread/greenlet so it won’t block the main thread from accepting calls</p><p>Using <a href="https://docs.python.org/3/library/asyncio-task.html#asyncio.run_coroutine_threadsafe">to_thread</a></p><p>A simple use case of that will be:</p><pre>import time<br>import asyncio <br><br>def blocking_io():<br>    print(f&quot;start blocking_io at {time.strftime(&#39;%X&#39;)}&quot;)<br>    # Note that time.sleep() can be replaced with any blocking<br>    # IO-bound operation, such as file operations.<br>    time.sleep(1)<br>    print(f&quot;blocking_io complete at {time.strftime(&#39;%X&#39;)}&quot;)<br><br>async def main():<br>    print(f&quot;started main at {time.strftime(&#39;%X&#39;)}&quot;)<br><br>    await asyncio.to_thread(blocking_io)<br>    print(f&quot;finished main at {time.strftime(&#39;%X&#39;)}&quot;)<br><br>asyncio.run(main())<br><br># Expected output:<br>#<br># started main at 19:50:53<br># start blocking_io at 19:50:53<br># blocking_io complete at 19:50:54<br># finished main at 19:50:54</pre><p>Using <a href="https://github.com/miguelgrinberg/greenletio">greenletio</a>, this library will use greenlets to bridge async and sync calls.</p><pre>import asyncio<br>from greenletio import async_<br>import time<br><br>@async_<br>def sync_function():<br>    print(f&quot;start blocking_io at {time.strftime(&#39;%X&#39;)}&quot;)<br>    time.sleep(1)<br>    print(f&quot;blocking_io complete at {time.strftime(&#39;%X&#39;)}&quot;)<br><br>async def main():<br>    print(f&quot;started main at {time.strftime(&#39;%X&#39;)}&quot;)<br>    await sync_function()<br>    print(f&quot;finished main at {time.strftime(&#39;%X&#39;)}&quot;)<br><br>asyncio.run(main())<br><br># Expected output:<br>#<br># started main at 19:50:53<br># start blocking_io at 19:50:53<br># blocking_io complete at 19:50:54<br># finished main at 19:50:54</pre><h3>2. Async calls</h3><p>This is a slightly easier situation to manage because there is no need for additional threads (necessarily) which could add complexity.</p><h4>Submit to existing loop</h4><p>Good for simple use cases where we want to run a light task on the current loop, will not be good for CPU heavy tasks as they will consume a lot of time of the loop and might hurt performance, but very simple to manage. good for sending api calls for analytics.</p><pre>import time<br>import asyncio<br><br><br>async def async_func():<br>    print(f&quot;start async_func at {time.strftime(&#39;%X&#39;)}&quot;)<br>    await asyncio.sleep(1)<br>    print(f&quot;async_func complete at {time.strftime(&#39;%X&#39;)}&quot;)<br><br><br>async def main():<br>    print(f&quot;started main at {time.strftime(&#39;%X&#39;)}&quot;)<br>    asyncio.create_task(async_func())<br>    print(f&quot;finished main at {time.strftime(&#39;%X&#39;)}&quot;)<br>    await asyncio.sleep(2) # just adds time for the loop to wait for the async response<br><br>asyncio.run(main())<br># results: <br># started main at 09:30:17<br># finished main at 09:30:17<br># start async_func at 09:30:17<br># async_func complete at 09:30:18<br># you can see the the main started and finished before async</pre><p>This is a simple solution, but be careful with creating Tasks if you are running multiple threads since tasks in python are not thread safe.</p><h4>Create a new thread with a loop</h4><p>A Good use cases for this one is where you are seeing a negative performance impact from the previous option where the task is running on the loop in the main thread.</p><pre>import time<br>import asyncio<br>from threading import Thread<br><br><br>async def async_func():<br>    print(f&quot;start async_func at {time.strftime(&#39;%X&#39;)}&quot;)<br>    await asyncio.sleep(1)<br>    print(f&quot;async_func complete at {time.strftime(&#39;%X&#39;)}&quot;)<br><br><br>async def main():<br>    print(f&quot;started main at {time.strftime(&#39;%X&#39;)}&quot;)<br>    # starts a new loop in a thread<br>    loop = asyncio.new_event_loop()  # assuming a loop is running if using fastapi<br>    thread = Thread(target=loop.run_forever)<br>    thread.start()<br>    asyncio.run_coroutine_threadsafe(async_func(), loop) # scheudle coro in loop<br>    print(f&quot;finished main at {time.strftime(&#39;%X&#39;)}&quot;)<br>    await asyncio.sleep(2)<br><br>    # stop loop and thread<br>    for task in asyncio.all_tasks(loop):<br>        if not task.done():<br>            task.cancel()<br>    loop.call_soon_threadsafe(loop.stop)<br><br>asyncio.run(main())<br># results: <br># started main at 09:30:17<br># finished main at 09:30:17<br># start async_func at 09:30:17<br># async_func complete at 09:30:18<br># you can see the the main started and finished before async</pre><p>By running tasks in another thread you step in the world of parallelism that presentness a new set of challenges.</p><p>Challenges of running async tasks in another thread (and loop):</p><ul><li>Race conditions — A race condition occurs when two threads access a shared variable at the same time. The first thread reads the variable, and the second thread reads the same value from the variable. Can be tricky with static objects and singletons (like api/db clients).</li><li>Asyncio loop sync — You cannot run a tasks that starts in one loop and ends in another.</li></ul><p>Hope you enjoyed!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c206312a6f56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python — DI (dependency injection ) — Part 2 — Containers]]></title>
            <link>https://snir-orlanczyk.medium.com/python-di-dependency-injection-part-2-containers-c621f4311d55?source=rss-d258e3808bbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/c621f4311d55</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Snir Orlanczyk]]></dc:creator>
            <pubDate>Wed, 29 Nov 2023 18:26:56 GMT</pubDate>
            <atom:updated>2023-11-29T18:26:56.728Z</atom:updated>
            <content:encoded><![CDATA[<h3>Python — DI (dependency injection ) — Part 2 — Containers</h3><p>In the previous article I covered the use of manual DI injections with lambda defaults, but it only covers very simple use cases and forces the inject class or the consuming class to import the dependency, which beats the purpose of <em>DIP </em>where we depend on an abstraction rather than the concrete class.</p><h3>What is a DI container?</h3><p>DI container is a type of implementation of the DI pattern, It manages the instantiation and lifetime of objects (dependencies) in an application and injects them into other objects that require them.</p><pre># class_a.py<br>from di import container<br>from typing import Protocol<br><br><br>class iClassA(Protocol):<br>  def do_someting():<br>    pass<br><br><br>class ClassA(iClassA):<br>  def do_someting():<br>    print(&quot;something&quot;)<br><br><br>container.register(iClassA, ClassA())</pre><pre># class_b.py<br>from di import container<br>from .class_a import iClassA<br><br>class ClassB:<br>  def __init(self):<br>    self.a = container.resolve(iClassA)<br>    self.a.do_something()</pre><p>This example illustrates the power of using a DI container, it makes using dependencies easy as we don’t need to manage the dependancy’s life cycle, or be aware of its concrete implementation.</p><h3>DI container frameworks</h3><p>This <a href="https://github.com/sfermigier/awesome-dependency-injection-in-python">repo</a> contains a list of common DI frameworks for python.</p><p>Each DI container solution is slightly different, but they all work mostly the same and implement a service locator pattern, but with different bells and whistles attached to it.</p><h3>Main features for DI containers</h3><p>Most DI container will have the following basic features that you need to be aware of it and see if it fits your needs</p><ul><li>Registry type — you should be able to register an object as memorized of factorized (singleton or transient).</li><li>auto-wire — allows you to resolve the dependencies in the init method without explicitly writing the resolving code (usually done with a decorator).</li><li>multiple containers — sometimes you will need to have multiple containers, but i found that usually it makes things more complicated and most things can be solved with a central container.</li></ul><h3>Abstracting the container</h3><p>To try and avoid being locked to a specific framework you can try and wrap the use of your container with your on calls, to minimize/prevent breaking changes if you ever need to replace it.</p><p>In this example I created a wrapper around <a href="https://github.com/kodemore/kink">kink</a>, i used it as a very simple DI container that covers all the basic needs, and the implementation of it is straight forward and simple to understand and review.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d76ecb996632b3bcd73f09c3574dba0/href">https://medium.com/media/4d76ecb996632b3bcd73f09c3574dba0/href</a></iframe><p>The abstraction creates a static container that can be used throughout the app in addition to a wrapper around the auto wire decorator and a bootstrap function as a single place to register the core dependancies in the app that should be loaded first (i.e logger).</p><h3>Conclusion</h3><p>Manual DI is a really good solution if you have a small low complexity app and you want to create loose coupling between your components.</p><p>A DI container is a great solution as well but it comes with higher adoption cost and more complexity, but provides more flexibility and features.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c621f4311d55" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VSCode setup for FastAPI]]></title>
            <link>https://snir-orlanczyk.medium.com/fastapi-project-in-vscode-7fa3e6fccdb2?source=rss-d258e3808bbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fa3e6fccdb2</guid>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ide]]></category>
            <dc:creator><![CDATA[Snir Orlanczyk]]></dc:creator>
            <pubDate>Thu, 05 Oct 2023 05:41:37 GMT</pubDate>
            <atom:updated>2023-10-05T14:03:28.960Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fG1LnMmoWwiemkfCcOWxOw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@6heinz3r?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Gabriel Heinzer</a> on <a href="https://unsplash.com/photos/EUzk9BIEq6M?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>I personally love VSCode way better than pyCharm, which seems to be the de-facto IDE for Python for a lot of developers, one of the things that it gives are sensible defaults for python that makes it easier to just start working, which is quite nice but you are giving up a flexible UI that has a lot of plugins, and with some simple configuration can be as good pyCharm and better!</p><h3>Creating a Venv</h3><p>from <a href="https://packaging.python.org/en/latest/guides/installing-using-pip-and-virtual-environments/#creating-a-virtual-environment">https://packaging.python.org/en/latest/guides/installing-using-pip-and-virtual-environments/#creating-a-virtual-environment</a></p><blockquote>venv allow you to manage separate package installations for different projects. They essentially allow you to create a “virtual” isolated Python installation and install packages into that virtual installation</blockquote><p>Having a venv is a very common practice for many languages as different project require different packages in different versions, managing it all on a global level is a recipe for disaster.</p><p>A venv can be created with the binaries of a specific python version, which can allow you to run different versions of python regardless of the system version</p><pre># To install a venv in your project, go to your project directory and run the following<br>python3 -m venv .venv<br><br># This command will create a .venv folder which will contain the python <br># binaries and packages for you project<br><br># to install a specifc python version run the following<br>virtualenv .venv --python=python3.9<br><br>#now the venv needs to be activated, to do so run<br>source .venv/bin/activate</pre><h3>Setting up a debugger</h3><p>To setup a debugger which is setup to run your FastAPI app add the following file at .vscode/launch.json</p><pre># .vscode/launch.json<br># assuming that the path to your FastAPI app file is at src/app/main.py.<br>{<br>  &quot;version&quot;: &quot;0.2.0&quot;,<br>  &quot;configurations&quot;: [<br>    {<br>      &quot;name&quot;: &quot;Python: Module&quot;,<br>      &quot;type&quot;: &quot;python&quot;,<br>      &quot;request&quot;: &quot;launch&quot;,<br>      &quot;module&quot;: &quot;src.app.main&quot;,<br>      &quot;env&quot;: { &quot;PYTHONPATH&quot;: &quot;${workspaceFolder}/src/&quot; }<br>    }<br>  ]<br>}</pre><p>Now when you go to the debugger there will an option to start the server with a debugger attached to it, which will allow the use of breakpoints.</p><h3>Setting up default settings</h3><pre># .vscode/settings.json<br>{<br>  &quot;[python]&quot;: {<br>    &quot;editor.defaultFormatter&quot;: &quot;ms-python.autopep8&quot;<br>  },<br>  &quot;python.testing.pytestArgs&quot;: [&quot;.&quot;],<br>  &quot;python.testing.pytestEnabled&quot;: true,<br>  &quot;python.terminal.activateEnvironment&quot;: true<br>}</pre><p>These settings will</p><ul><li>setup pytest as the testing framework</li><li>Attempt to discover all test files, and will allow you to run tests from the tests tab</li><li>will auto activate the venv in the VSCode terminal</li><li>Will setup a autopep8 as a formatter (to make it work you need to install the autopep8 extension)</li></ul><h3>Settings up common extension for you team</h3><p>To make sure you are all using the same tool you can add the extensions you are using to .vscode/extensions.json</p><pre># .vscode/extensions.json<br>{<br>  &quot;recommendations&quot;: [&quot;ms-python.autopep8&quot;]<br>}</pre><p>Hope you enjoyed!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fa3e6fccdb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python — DI (dependency injection )]]></title>
            <link>https://snir-orlanczyk.medium.com/python-di-dependency-injection-710edc054e93?source=rss-d258e3808bbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/710edc054e93</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Snir Orlanczyk]]></dc:creator>
            <pubDate>Wed, 04 Oct 2023 22:30:06 GMT</pubDate>
            <atom:updated>2023-11-29T18:28:17.897Z</atom:updated>
            <content:encoded><![CDATA[<h3>Python — DI (dependency injection ) — Part 1</h3><p>Dependency injection is a pattern that promote loose coupling between components. it implements the IoC (Inversion of Control) and DiP (Dependency Inversion Principle) principles and can help make our components smaller, more testable, and expose the dependency and connections between components, which increase maintainability.</p><h3>Principles of DI</h3><p>So first lets break it down to the principles</p><h4><strong>DIP — Dependency Inversion Principle</strong></h4><blockquote>DIP suggests that high-level modules should not depend on low level modules. Both should depend on abstraction.</blockquote><p>In a more practical sense, a concrete class should not be directly dependent on another concrete class, rather be dependent on an interface (a protocol) which a concrete class will later implement.</p><h4>IoC — Inversion of Control</h4><blockquote>IoC is a design principle which recommends the inversion of different kinds of controls in object-oriented design to achieve loose coupling between application classes. In this case, control refers to any additional responsibilities a class has, other than its main responsibility, such as control over the flow of an application, or control over the dependent object creation and binding.</blockquote><p>In simple terms, IoC is a principle that allows a software component to receive its dependencies from an external source. This is in contrast to traditional software design, where a component is responsible for creating and managing its own dependencies.</p><h4>DI — Dependency Injection</h4><blockquote>Dependency Injection (DI) is a design pattern which implements the IoC principle to invert the creation of dependent objects.</blockquote><p>DI is the actual implementation of the IoC principle.</p><h3>DI in python</h3><p>Generally the are multiple approaches in how to implement DI in a project and it can depend on multiple factor such as scale and complexity of the project.</p><h4>Manual DI</h4><p>Manual DI is when we manually wire up each component with its dependancies.</p><p>Manual DI can happen either via initializer, method or parameter.</p><pre># example for initializer DI<br><br>class DependencyA(Protocol):<br>  def do_something(self):<br>    pass<br><br>class ClassA(DependencyA)<br>  def do_something(self):<br>    pass<br><br>class SomeClass:<br>  def __init__(self, dep: DependencyA):<br>    self.dep = dep<br><br><br>some_class = SomeClass(dep=ClassA)</pre><p>In this example we are injecting the class with an abstract dependency in the initializer, and whomever initiates <strong>SomeClass</strong> is responsible to provide it with its dependencies first.</p><p>We usually know what are the concrete dependencies for the class so we can implement the same solution with sensible defaults.</p><pre># example for initializer DI with sensible defaults<br><br>class DependencyA(Protocol):<br>  def do_something(self):<br>    pass<br><br>class ClassA(DependencyA)<br>  def do_something(self):<br>    pass<br><br>class SomeClass:<br>  def __init__(self, dep: DependencyA = lambda: ClassA()):<br>    self.dep: DependencyA = dep()<br><br># simpler init for the class + the same flexiblity as before<br>some_class = SomeClass()</pre><p>Why us a a lambda though? well if we did something like this for the init method:</p><pre>class SomeClass:<br>  def __init__(self, dep: DependencyA = ClassA()):<br>    self.dep = dep</pre><p>ClassA will be initiate even without initializing <strong>SomeClass</strong> since we are calling the init for <strong>ClassA</strong> in the function signature.</p><p>The solution with the lambda protects us from that and gives <strong>SomeClass</strong> control on when to initialize <strong>ClassA</strong>.</p><h4>DI Container</h4><p>A DI container is a framework that is used to manage DI throughout the application, the DI container will have a mapping of components registered to it, and it will resolve them upon request.</p><p>This <a href="https://github.com/sfermigier/awesome-dependency-injection-in-python">repo</a> contains a list of common DI frameworks for python.</p><p>Each DI container solution is slightly different, but they all work mostly the same and implement a service locator pattern, but with different bells and whistles attached to it.</p><p>Most DI containers allow control over the life cycle of the component, it control if it will be initiated every time it is injected, or will it be a singleton? This allows for more flexibility as the implemented component does not manage its own life cycle and can be injected in different ways.</p><p>Read <a href="https://snir-orlanczyk.medium.com/python-di-dependency-injection-part-2-containers-c621f4311d55"><strong>Part 2 — containers</strong></a> for learning more about DI with Containers and how to use them</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=710edc054e93" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python — Composable Analytics Reporter]]></title>
            <link>https://snir-orlanczyk.medium.com/python-composable-analytics-reporter-8748a69c0a06?source=rss-d258e3808bbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/8748a69c0a06</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[composition]]></category>
            <dc:creator><![CDATA[Snir Orlanczyk]]></dc:creator>
            <pubDate>Wed, 04 Oct 2023 05:05:51 GMT</pubDate>
            <atom:updated>2023-10-04T14:46:51.673Z</atom:updated>
            <content:encoded><![CDATA[<h3>Python — Composable Analytics Reporter</h3><p>This is a concept I was thinking about for creating a composable generic analytics reporter for a python app. the idea is to create a component that is flexible and can adopt in multiple ways of processing and sending logs, and also allows to send to multiple receivers and handle multiple contracts.</p><h3>Getting started</h3><p>First lets break down into components</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RKE90ZU1b81NwulIifi1vQ.png" /></figure><p>For both ApiClient and event processing i use a strategy pattern to maintain a flexible and easy to use interface</p><p>I also use DI to inject the components to each other, which makes the connections between them loose and promotes a composable design.</p><h3><strong>EventProcessingStrategy</strong></h3><p>We will get started by creating the abstract class. it gets an APIClient protocol and defines the `send_event` method.</p><pre>from abc import ABC, abstractmethod<br>from .api_client import AnalyticsAPIClient<br><br><br>class EventProcessingStrategy(ABC):<br>    def __init__(self, api_client: lambda: AnalyticsAPIClient()) -&gt; None:<br>        self.api_client: AnalyticsAPIClient = api_client()<br>        super().__init__()<br><br>    @abstractmethod<br>    async def send_event(self, event_data: dict) -&gt; None:<br>        pass<br><br>    async def _send(self, data):<br>        await self.api_client.send(data)</pre><p>Next, we will create concrete strategies.</p><p><strong>Stream</strong></p><p>Simply sending the request to the api client.</p><pre>class StreamStrategy(EventProcessingStrategy):<br>    async def send_event(self, event_data: dict) -&gt; None:<br>        await self._send(event_data)<br></pre><p><strong>Batch</strong></p><p>Obviously batching is more complicated because there are more moving piece but lets break it down.</p><pre>import asyncio<br>import json<br>from time import time<br>from typing import Protocol<br><br>from .api_client import AnalyticsAPIClient<br>from .strategy_protocl import EventProcessingStrategy<br><br><br>class EventsStore(Protocol):<br>    def append(self, event):<br>        pass<br><br>    def clear(self, event):<br>        pass<br><br>    def size(self, event):<br>        pass<br><br><br>class InMemoryStore(EventsStore):<br>    def __init__(self) -&gt; None:<br>        self.store = []<br>        super().__init__()<br><br>    def append(self, event):<br>        self.store.append[event]<br><br>    def clear(self):<br>        self.store.clear()<br><br>    def size(self) -&gt; int:<br>        return len(self.store)<br><br><br>class BatchStrategy(EventProcessingStrategy):<br>    def __init__(self,<br>                 api_client=lambda: AnalyticsAPIClient(),<br>                 store=lambda: InMemoryStore(),<br>                 batch_size=10,<br>                 batch_interval=5):<br>        self.api_client: AnalyticsAPIClient = api_client()<br>        self.batch_size = batch_size<br>        self.batch_interval = batch_interval<br>        self.event_store: EventsStore = store()  # Buffer to store events<br>        self.last_batch_time = time()<br>        self.lock = asyncio.Lock()<br>        asyncio.create_task(self.send_events_periodically())  # Start the periodic event sender in the background<br><br>    async def send_event(self, event_data):<br>        self.event_store.append(event_data)<br><br>        # Check if the batch size or interval is reached and send events if needed<br>        if self.event_store.size &gt;= self.batch_size or \<br>                (time() - self.last_batch_time) &gt;= self.batch_interval:<br>            # asyncio.ensure_future(self._send_batch())<br>            await self._send_batch()<br>        return<br><br>    async def _send_batch(self):<br>        async with self.lock:<br>            if not self.event_store:<br>                return  # Nothing to send<br><br>            try:<br>                payload = json.dumps(self.event_store)<br>                _, status_code = await self.api_client.send(payload)<br><br>                if status_code == 200:<br>                    print(&quot;Batch sent successfully&quot;)<br>                    self.event_store.clear()  # Clear the buffer after successful send<br>                    self.last_batch_time = time()<br>                else:<br>                    print(f&quot;Failed to send batch. Status code: {status_code}&quot;)<br><br>            except Exception as e:<br>                print(f&quot;Error sending batch: {str(e)}&quot;)<br><br>    async def send_events_periodically(self):<br>        while True:<br>            await asyncio.sleep(self.batch_interval)<br>            await self._send_batch()</pre><p>We define a batch size and interval, when a request comes in if the number of requests reaches the batch size or if the timestamp since last send diff from now is bigger than the interval it will trigger a send, additionally there is a periodic call to try and send events that are in the store (in case it has been a while between events).</p><p>I added an async lock to prevent race conditions where multiple calls to send a batch are being sent to close together and it will risk sending duplicates (will hurt data integrity).</p><p>Also there is a store that keeps the buffered events rather than a simple array, and same as the api client, this allows flexibility to swap the implementation without breaking the logic.</p><h3>APIClient</h3><p>The API client manages the sending of the data (batched or single event) and can have multiple implementations.</p><pre>class AnalyticsAPIClient(Protocol):<br>    async def send(self, data: dict) -&gt; int:<br>        pass</pre><p>for example</p><pre># A mocked client that just returns prints the data and sleep<br>class MockAPIClient(AnalyticsAPIClient):<br>    async def send(self, data: dict) -&gt; int:<br>        print(data)<br>        await asyncio.sleep(0.5)<br>        return data, 200<br><br># or an API client that sends it to a server<br>import httpx<br><br>class SomeServerAPIClient(AnalyticsAPIClient):<br>    async def send(self, data: dict) -&gt; int:<br>        async with httpx.AsyncClient() as client:<br>            httpx.post(&quot;https://somewebserver.org/post&quot;, json=data)<br><br># or event send events to kafka<br>class KafkaClient(AnalyticsAPIClient):<br>    async def send(self, data: dict) -&gt; int:<br>        # send requests to kafka<br>        pass<br></pre><p><strong>Extending the API client</strong></p><p>If we want to send our analytics to multiple targets we can add an AnalyticsAPIManager component that will hold a list of APIClients and will manage the sending to all registered clients, having multiple target can be useful for things like console logging and tracking at multiple systems.</p><h3>AnalyticsReportingClient</h3><p>This is the component that ties it all together and and provides a simple interface to interact with.</p><p>For performance and also maintaining its context it is a good idea to make the the AnalyticsReportingClient a singleton.</p><pre>import asyncio<br><br>@singleton<br>class AnalyticsReportingClient:<br>    _instance = None<br>    <br>    def __new__(cls): # making this class a singleton (ensures a single instance only)<br>        if cls._instance is None:<br>            cls._instance = super(AnalyticsClient, cls).__new__(cls)<br>        return cls._instance<br><br>    def __init__(self,<br>                 api_client=lambda: SomeServerAPIClient(),<br>                 strategy=lambda api_client: BatchStrategy(api_client)) -&gt; None:<br>        self.strategy: EventProcessingStrategy = strategy(api_client)<br><br>    async def send(self, event_data: dict):<br>        await self.strategy.send_event(event_data)</pre><h3>Using it</h3><p>To use this analytics client, just initialize it, send an event, and take a sip of coffee.</p><pre>client = AnalyticsClient()<br>await client.send({&quot;oh&quot;: &quot;no1&quot;})</pre><p>Done.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8748a69c0a06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FastAPI — rate limit middleware]]></title>
            <link>https://snir-orlanczyk.medium.com/fastapi-rate-limit-middleware-ec9e46f84cdb?source=rss-d258e3808bbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec9e46f84cdb</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Snir Orlanczyk]]></dc:creator>
            <pubDate>Wed, 04 Oct 2023 04:03:10 GMT</pubDate>
            <atom:updated>2024-03-03T02:47:53.444Z</atom:updated>
            <content:encoded><![CDATA[<h3>FastAPI — rate limit middleware</h3><p>There are many cases where we would want to have a rate limiting mechanism in web app (i.e defend against over using an expensive/external/external &amp; expensive service).</p><h3>So why middle?</h3><p>Well it is just a convenient place to place something like a rate limiter since it capture the request and can block it before CPU heavy tasks are done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kHi1q4EeQ99JqlTbaNnyQA.png" /></figure><p>as illustrated, a middleware simply allow to intercept the requests internally.</p><h3>Getting started</h3><p>for start, i am using <a href="https://github.com/alisaifee/limits">limits</a> package to maintain the rate limiting window, it is a simple package that allows to multiple storage options and implements multiple algorithms, and supports both sync and async implementations.</p><pre># limits_wrapper.py<br><br>from limits import RateLimitItem, RateLimitItemPerMinute, storage, strategies<br><br>REDIS_URL: str = &quot;redis://localhost:6379/0&quot;<br>storage = storage.RedisStorage(REDIS_URL)<br>throttler = strategies.MovingWindowRateLimiter(storage)<br><br>&quot;&quot;&quot;<br>    This component is used as a wrapper for `limits` so we won&#39;t use its api directly in the throttler class.<br>&quot;&quot;&quot;<br><br><br>def hit(key: str, rate_per_minute: int, cost: int = 1) -&gt; bool:<br>    &quot;&quot;&quot;<br>        Hits the throttler and returns `true` if a request can be passed and `false` if it needs to be blocked<br>        :param key: the key that identifies the client that needs to be throttled<br>        :param rate_per_minute: the number of request per minute to allow<br>        :param cost: the cost of the request in the time window.<br>        :return: returns `true` if a request can be passed and `false` if it needs to be blocked<br>    &quot;&quot;&quot;<br>    item = rate_limit_item_for(rate_per_minute=rate_per_minute)<br>    is_hit = throttler.hit(item, key, cost=cost)<br>    return is_hit<br><br><br>def rate_limit_item_for(rate_per_minute: int) -&gt; RateLimitItem:<br>    &quot;&quot;&quot;<br>    Returns the rate of requests for a specific model<br><br>    :param rate_per_minute: the number of request per minute to allow<br>    :return: `RateLimitItem` object initiated with a rate limit that matched the model<br>    &quot;&quot;&quot;<br>    return RateLimitItemPerMinute(rate_per_minute)</pre><p>This section wraps the usage of the limits library and exposes its functionality through our module, which will make it easier easier to manage the touch points with the library in case we want to replace it.</p><h3>Rate limiting logic</h3><p>Now we need to write the class that will manage the rate limiting with the library</p><pre>from starlette.requests import Request<br>from starlette.exceptions import HTTPException<br>from starlette.status import HTTP_429_TOO_MANY_REQUESTS<br><br>from .limits_wrapper import hit<br><br>class RateLimitMiddleware:<br>    async def __call__(self, request: Request):<br>        key = &quot;some-key&quot;<br>        rate = 100<br><br>        if not hit(key=key, rate_per_minute=rate):<br>            raise HTTPException(status_code=HTTP_429_TOO_MANY_REQUESTS, detail=&quot;request limit reached&quot;)</pre><h3>Adding flexibility</h3><p>But this logic is hard coded and does not add much we can easily improve it by allowing to pass functions that will allow to customize the usage of the class</p><pre>class RateLimitMiddleware:<br>    def __init__(<br>        self,<br>        identifier: Callable[[Request], Awaitable[str]],<br>        callback: Callable[[Request], Awaitable[Any]],<br>        rate_provider: Callable[[Request], Awaitable[int]]<br>    ):<br>        self.identifier = identifier<br>        self.callback = callback<br>        self.rate_provider = rate_provider<br><br>    async def __call__(self, request: Request):<br>        callback = self.callback<br>        identifier = self.identifier<br>        rate_provider = self.rate_provider<br><br>        key = await identifier(request)<br>        rate = await rate_provider(request)<br><br>        if not hit(key=key, rate_per_minute=rate):<br>            return await callback(request)</pre><p>by introducing these function parameter we can provide custom logic to will generate what we need.</p><h3>Adding sensible defaults</h3><p>We can even include default implementations of them if it makes sense for our use case, for example we want to enforce rate limiting for each ip as a default, or also return an HTTP 429 by default when the rate limit has been reached.</p><pre>async def identifier(request: Request) -&gt; str:<br>  ip = request.client.host<br>  return ip<br><br>async def _default_callback(request: Request):<br>    raise HTTPException(status_code=HTTP_429_TOO_MANY_REQUESTS, detail=&quot;request limit reached&quot;)<br><br>class RateLimitMiddleware:<br>    def __init__(<br>        self,<br>        identifier: Callable[[Request], Awaitable[str]] = identifier,<br>        callback: Callable[[Request], Awaitable[Any]],<br>        rate_provider: Callable[[Request], Awaitable[int]]<br>    ):<br>        self.identifier = identifier<br>        self.callback = callback<br>        self.rate_provider = rate_provider<br><br>    async def __call__(self, request: Request):<br>        callback = self.callback<br>        identifier = self.identifier<br>        rate_provider = self.rate_provider<br><br>        key = await identifier(request)<br>        rate = await rate_provider(request)<br><br>        if not hit(key=key, rate_per_minute=rate):<br>            return await callback(request)</pre><h3>Using the Rate limiter</h3><p>If we want to set our rate limit to 1000 requests per minute, and use the default callback and identifier:</p><pre>async def rate_provider(request: Request) -&gt; str:<br>  return 1000<br><br><br>rate_limit = RateLimitMiddleware(rate_provider=rate_provider)</pre><h4>Integrating with FastAPI</h4><p>To integrate it with FastAPI I prefer to add it as a dependency since it means it can be applied per route/router/app, which gives a lot of flexibility, unlike when we use it as a starlette middleware which forces us to you us it on an app wide level.</p><pre>from fastapi import FastAPI, Depends<br>from app.middlewares.rate_limiter import RateLimitMiddleware<br><br>app = FastAPI()<br><br><br>@app.get(&quot;/&quot;, dependencies=[Depends(RateLimitMiddleware())])<br>async def root():<br>    return {&quot;message&quot;: &quot;OK!&quot;}<br></pre><p>adding the following dependency to a route/router will enforce the rate limiting on it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec9e46f84cdb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS CI Separating build & test jobs on Gitlab]]></title>
            <link>https://snir-orlanczyk.medium.com/ios-ci-separating-build-test-jobs-on-gitlab-409a540dbef8?source=rss-d258e3808bbf------2</link>
            <guid isPermaLink="false">https://medium.com/p/409a540dbef8</guid>
            <category><![CDATA[automation-testing]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Snir Orlanczyk]]></dc:creator>
            <pubDate>Sat, 11 Jun 2022 18:02:10 GMT</pubDate>
            <atom:updated>2022-06-24T15:11:03.556Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AF5Fj3D3a0uX5qC2IBJSVQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@bannon15?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Bannon Morrissy</a> on <a href="https://unsplash.com/s/photos/split?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Usually when running automated test on CI we will have testing suites that run (like unit test/integration/etc..). When developing mobile applications with Swift we need to compile our testing targets before we can run them, usually the simpler solution is to run them together as a single CI job. I will try to explore the option of breaking building and testing into separate CI jobs.</p><h3>TL;DR</h3><p>If you have a single testing target you are probably better off building and testing at the same CI job, if you have more it is a different story.</p><h3>Tools</h3><p>I will be using the following tools to for running the build &amp; test</p><ul><li>Gitlab for CI and Hosting</li><li>Fastlane for writing the xCode actions</li></ul><h3>Build for testing</h3><p>When writing a test for an iOS app on xCode we have the option to build for testing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*VufnA6FGPkZH9jKN74cXdA.png" /><figcaption>Build for testing</figcaption></figure><p>Running this will compile the app into a testable package that contains the code from the testing target that is defined in the scheme that we are building.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*Z-X52iJOMsFiNTxzCflJig.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*4NOqbKOSLfuOtmLokzevbA.png" /><figcaption>Scheme settings</figcaption></figure><p>This type of package that is produced by the build for testing is.xctest , and xcode will create an .xctest package for each testing target in the scheme.</p><p>The packages can be quite large as the contain all the app code and dependancies as well as the testing code and config.</p><h4>Using fastlane for building</h4><p>fastlane gives us a very convenient tool to use called <a href="https://docs.fastlane.tools/actions/scan/">scan</a>, which essentially wraps xcode-build and other API’s into a very easy to use tool. we can run scan as follows in order to create a build for testing for a specific scheme.</p><pre>lane :build_for_testing do<br>   scan(scheme: &quot;BuildAndTest&quot;<br>   derived_data_path: &quot;build&quot;,<br>   build_for_testing: true )<br>end</pre><ul><li><strong>scheme</strong>: defines which scheme to use</li><li><strong>derived_data_path</strong>: changes the default derivedData folder path for the build, this allows us easy access to the build artifacts</li><li><strong>build_for_testing</strong>: builds the scheme for testing</li></ul><h3>Testing compiled packages</h3><p>Now that we have the compile .xctest files we can run the tests.</p><p>We will use scan again to run the tests.</p><pre>lane :test do<br>   scan(scheme: &quot;BuildAndTest&quot;<br>   derived_data_path: &quot;build&quot;,<br>   test_without_building: true )<br>end</pre><ul><li><strong>derived_data_path</strong>: must be the same as the build lane so that the script will be able to find the compiled packages.</li><li><strong>test_without_building</strong>: will attempt to run the tests for a provided compiled package.</li></ul><h3>Running build &amp; test in separate job on CI</h3><p>If we were to run both lanes in the same CI job as follows it would build and test the our code</p><pre>build_and_test:<br>   script:<br>   - fastlane build_for_testing<br>   - fastlane test</pre><p>But say that we want to run the testing in a separate job, all we will have to do is create 2 stages (because testing depends on building to finish and they can’t run at the same time), and make sure to pass the .xctest packages to the testing job. it would look something like this:</p><pre>stages:<br>- build<br>- test</pre><pre>build:<br>   stage: build<br>   script: <br>   - fastlane build_for_testing<br>   artifacts:<br>      when: on_success<br>      paths:<br>      - build/**/*.xctest</pre><pre>test:<br>   stage: test<br>   script:<br>   - fastlane test</pre><p>What we did here is we defined 2 jobs build and test . build will run first, creating the .xctest files and uploading then to the gitlab pipeline artifact storage (if built finish successful). Then test will run, the artifact are part of the pipeline, they maintain their original folder structure, and are available to all jobs that are running in the following stage by default, so test will have the build folder with our .xctest files available for running, and all it does is running the tests.</p><h3>Conclusions</h3><p>pros —</p><ul><li>Better separation of CI pipeline and actions, making them more atomic, which makes it easier to understand if a pipeline failed and where just by looking at the pipeline</li><li>Re-run flaky tests — if we have a flaky test suite we can re-run very quickly because we do not need to wait for the code to compile.</li></ul><p>cons —</p><ul><li>It can take more time — from my testing it takes about 1–2~ more minutes for the whole process of running a testing suite, the reason being that we need to upload and download big artifacts at the start and end of every build + checking out the git branch again, those process together take about 1–2 minutes.</li></ul><p>I think that this can be very beneficial in certain cases, imagine that you have 3 testing suites in your project, you can compile them all in a single job, that will produce 3 different testing packages where each can be tested in its own job, that would actually save time because we only have to build once, and re-running a test would be very fast.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=409a540dbef8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>