<?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 casper orich on Medium]]></title>
        <description><![CDATA[Stories by casper orich on Medium]]></description>
        <link>https://medium.com/@orichcaspertheghost?source=rss-4c803599bd94------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*te6bIFc8-u-Hgj9gbU1EYA.jpeg</url>
            <title>Stories by casper orich on Medium</title>
            <link>https://medium.com/@orichcaspertheghost?source=rss-4c803599bd94------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 13:16:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@orichcaspertheghost/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[Python Generic Typing: Applications beyond DSA]]></title>
            <link>https://medium.com/@orichcaspertheghost/python-generic-typing-applications-beyond-dsa-c6e77f999043?source=rss-4c803599bd94------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6e77f999043</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[mypy]]></category>
            <category><![CDATA[python-typing]]></category>
            <dc:creator><![CDATA[casper orich]]></dc:creator>
            <pubDate>Wed, 09 Sep 2026 07:39:19 GMT</pubDate>
            <atom:updated>2026-09-09T07:39:19.525Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ozbd_MTjnq984yEo" /><figcaption>Photo by <a href="https://unsplash.com/@cdr6934?utm_source=medium&amp;utm_medium=referral">Chris Ried</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When type hinting was introduced in Python, I was one of those who believed it was a pointless introduction- complexity for the sake of complexity. I believed it was created by developers who came from the world of static typing and were unwilling to bend to the might of Python’s dynamic typing. Sacrilege even, I would think. But when my workplace forced me to use a statically typed language, after months of stubbornness, I finally understood the pitfalls that static typing helps you avoid. I also learnt how development, especially with modern IDEs with IntelliSense(and similar), is so much easier with static typing. Now, I am a type-hinting evangelist for Python. What a turnaround.</p><h4>Cutting to the chase.</h4><p>Anyway, let’s jump right in: generic typing. It’s nothing new; you have already seen it, maybe just didn’t know what you were looking at. list[str] says this is a list of strings, but it doesn’t have to be strings; it could be ints list[int], bools list[bool], etc. That is what is called a generic type; a type that could be any type.</p><p>Now, those are built-in generics; you can actually define your very own generic types.</p><h4>New Python nomenclature</h4><p>It used to be that defining a generic type required you to define a TypeVar.</p><pre>from typing import TypeVar, Generic<br><br>T = TypeVar(&#39;T&#39;)<br><br>#defining a generic stack DS<br>class Stack(Generic[T]):<br>    #stack logic here<br></pre><p>However, Python 3.12 moving forward removed that requirement, so you can go straight to this.</p><pre>#defining a generic stack DS, no TypeVar necessary<br>class Stack[T]:<br>    def __init__(self) -&gt; None:<br>        # Create an empty list with items of type T<br>        self.items: list[T] = []<br><br>    def push(self, item: T) -&gt; None:<br>        self.items.append(item)<br><br>    def pop(self) -&gt; T:<br>        return self.items.pop()<br><br>    def empty(self) -&gt; bool:<br>        return not self.items</pre><p>This is much cleaner, and a statement of intent for how Python cares about type hinting.</p><h4>DSA usage</h4><p>You can already see how generics are useful in a DSA setup. In the example above, the stack does not need to know what type the items are; the push, pop, and empty operations can work on any type.</p><h4>Beyond DSA</h4><p>Ninety percent of developers work on real-world codebases, not conjured-up scenarios designed for technical interviews, and so I would like to show you how this concept can be applied beyond DSA problems.</p><p>Let’s take an example: you work in a fintech startup and have been tasked with designing a payment processor. It has to have the ability to handle multiple payment types. For starters, bank and card, but more will come later as the startup gets funding/revenue. I realize that this statement sounds like an interview scenario, but bear with me.</p><p>You know that a payment will always have an amount and a currency, and since you listened well to your OOP class, you know that inheritance is one way to achieve generics(technically).</p><p>So, your approach might look something like this.</p><pre>from dataclasses import dataclass, fields<br><br>@dataclass<br>class PaymentMetadata:<br>    amount: float<br>    currency: str<br><br><br>@dataclass<br>class CardMetadata(PaymentMetadata):<br>    card_token: str<br><br><br>@dataclass<br>class BankMetadata(PaymentMetadata):<br>    account_number: str</pre><p>And have the processor choose an execution path based on what metadata is passed in.</p><pre>class PaymentProcessor:<br><br>    def process(self, metadata):<br><br>        if isinstance(metadata, CardMetadata):<br><br>            # Card-specific logic<br>            # charge card...<br>            pass<br><br>        elif isinstance(metadata, BankMetadata):<br><br>            # Bank-specific logic<br>            # initiate bank transfer...<br>            pass</pre><p>This will work perfectly fine; the caller doesn’t need to know what kind of data goes in as that will be handled inside the processor.</p><pre>processor = PaymentProcessor()<br><br>processor.process(card_data)<br>processor.process(bank_data)</pre><p>The problem appears when the system starts to grow; now your supposed generic processor starts becoming not so generic. Every time you introduce a new payment type, you have to modify the processor.</p><pre>if isinstance(...):<br>    ...<br>elif isinstance(...):<br>    ...<br>elif isinstance(...):<br>    ...<br>elif isinstance(...):<br>    ...<br>elif isinstance(...):<br>    ...</pre><h4>Solution</h4><p>To make it truly generic, you don’t want the processor to care about what type of payment gets in. But there is a problem: you also want the payment to be a subtype of PaymentMetadata because that already has your amount and currency defined. What can you do?</p><h4>Bounded Generics.</h4><p>Python allows you to define a custom generic type, but then enforce that the type must be a subtype of something else. The syntax is simple; for older Python 3.12 and earlier:</p><pre>T = TypeVar(&quot;T&quot;, bound=SomeBaseType)<br><br>class YourGenericType[T]:</pre><p>But with the newer stuff, 3.12 onwards.</p><pre>class YourGenericType[T: SomeBaseType]:</pre><p>That tells a static type checker that <em>T</em> can be any type related to SomeBaseType.</p><h4>Putting it all together</h4><p>Your payment processor can then look like this.</p><pre><br>@dataclass<br>class PaymentResponse():<br>    status:bool<br>    extraMeta:dict[str,Any]<br><br>class PaymentProcessor[T: PaymentMetadata]:<br><br>    def process(self, metadata: T) -&gt; PaymentResponse:<br>        print(<br>            f&quot;Processing {metadata.amount} &quot;<br>            f&quot;in {metadata.currency}&quot;<br>        )<br><br>        default_fields = {&quot;amount&quot;, &quot;currency&quot;}<br><br>        extraMeta = {<br>            field.name: getattr(metadata, field.name)<br>            for field in fields(metadata)<br>            if field.name not in default_fields<br>        }<br><br>        return PaymentResponse(<br>            status=True,<br>            extraMeta=extraMeta<br>        )</pre><p>I have introduced a PaymentResponse type so that the processor has a defined return type. Notice that the process() function now accepts generic metadata, but that is bound to type PaymentMetadata. A static type checker will catch it if we try to pass in something that is not a subtype of PaymentMetadata, so extra security is added.</p><p>The payment processor can now work on any type of payment as long as it’s related to type PaymentMetadata.</p><h4>Strategy pattern</h4><p>There are still some flaws to the processor. You will still have to branch through logic depending on the exact type of payment metadata passed if you want to implement type-specific logic inside the processor.</p><p>You can eliminate this by combining a strategy pattern with generic typing for a much more robust and scalable solution. Instead of putting a giant if/elif inside PaymentProcessor, we can give each payment type its own strategy.</p><pre>class Paymentstrategy[T: PaymentMetadata]:<br><br>    def process(self, metadata: T) -&gt; None:<br>        pass<br><br>#Then implement the strategies:<br>class BankStrategy(Paymentstrategy[BankMetadata]):<br><br>    def process(self, metadata: BankMetadata):<br>        print(<br>            f&quot;Bank data Processing, amount is {metadata.amount} &quot;<br>            f&quot;in {metadata.currency}&quot;<br>        )<br><br>class CardStrategy(Paymentstrategy[CardMetadata]):<br><br>    def process(self, metadata: CardMetadata):<br>        print(<br>            f&quot;Card data Processing, amount is {metadata.amount} &quot;<br>            f&quot;in {metadata.currency}&quot;<br>        )</pre><p>Then you can have a strategy registry.</p><pre>#strategy registry<br>strategies = {<br>    BankMetadata: BankStrategy(),<br>    CardMetadata: CardStrategy(),<br>}</pre><p>and to use a strategy;</p><pre><br>card_data = CardMetadata(<br> amount=100,<br> currency= &quot;JPY&quot;,<br> card_token= &quot;LNO&quot;<br>)<br><br>bank_data = BankMetadata(<br> amount=100,<br> currency= &quot;JPY&quot;,<br> account_number=&quot;99000&quot;<br>)<br><br><br>strategy = strategies[type(bank_data)]<br>strategy.process(bank_data)<br><br>strategy = strategies[type(card_data)]<br>strategy.process(card_data)</pre><p>Now, getting in a new payment type is as easy as adding a new strategy class that can handle the metadata for that payment method, and registering that to your strategy registry is super easy.</p><pre>#strategy registry<br>strategies = {<br>    BankMetadata: BankStrategy(),<br>    CardMetadata: CardStrategy(),<br>    CryptoMetadata: CryptoStrategy(),#new strategy goes here<br>}</pre><p>And you don’t have to edit a PaymentProcessor class that contains long branching logic. Much cleaner, don’t you think?</p><h4>Conclusion</h4><p>Generic typing is not just for DSA; you can utilize it to make your code cleaner and easier to scale. By combining it with already existing patterns as I did here, you have the power to make your code much more robust.</p><p>Stay passionate. Keep coding; AI is not coming for your job… I think :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6e77f999043" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Twelve-Factor Python App.]]></title>
            <link>https://medium.com/@orichcaspertheghost/the-twelve-factor-python-app-ae631dca450a?source=rss-4c803599bd94------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae631dca450a</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[scaling-agile]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[casper orich]]></dc:creator>
            <pubDate>Thu, 16 May 2024 06:14:52 GMT</pubDate>
            <atom:updated>2024-05-16T06:14:52.008Z</atom:updated>
            <content:encoded><![CDATA[<p>As a Python developer, you most likely work on a software-as-a-service (saas) product, often referred to as a web app. The twelve-factor app is a methodology for building these types of apps. It was developed by a group of seasoned professionals who have most likely developed, deployed, and scaled more SAAS apps than you have.</p><p>Their experiences and observations are synthesized in <a href="https://12factor.net/">this document</a>. They pay particular attention to the dynamics of the organic growth of an app over time, the dynamics of collaboration between developers, and avoiding the cost of <a href="https://en.wikipedia.org/wiki/Software_rot">software erosion</a>.</p><p>In this article, I will condense the twelve-factor app into a short (relative to the original document) cheatsheet specifically for Python developers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FhqOR9zvzF63lq4Z" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. Codebase</h3><p>Ensure that your application code is managed within a version control system like Git. Each application should have a single code repository, containing all the necessary code and resources.</p><p>It’s important to note that multiple code repositories for a single application would signify a distributed system rather than a twelve-factor app. In such cases, it’s advised that you refactor shared code into libraries that can be included through dependency management tools like pip.</p><p>You should maintain a one-to-one relationship between the codebase and the deployed instances of their application. Each deployed instance, whether in production, staging, or a developer’s local environment, represents a ‘deploy’ of the same codebase.</p><p>While different deploys may run different versions of the application code, For instance, local commits not yet deployed to staging or production, they should all stem from the same codebase, ensuring consistency across the application’s various instances.</p><h3>2. Dependencies</h3><p>Do not rely on system-wide packages, instead specify all of your dependencies precisely in a dependency declaration manifest. This means listing all dependencies in a `requirements.txt` file using Pip. This ensures consistency between deploys.</p><p>Dependency isolation is equally important, it prevents external dependencies from affecting the application. You can achieve this by creating isolated environments with virtualenv, this way, only the dependencies within the environment are utilized during execution.</p><p>Notice how explicit dependency declaration simplifies the setup process for new developers joining the project. By simply running a deterministic build command, such as pip install -r requirements.txt, new developers can set up their development environment with minimal effort.</p><p>Additionally, twelve-factor apps avoid relying on system tools like the shell or curl, as their availability and compatibility cannot be guaranteed across different systems. If such tools are necessary, they should be vendored into the application to ensure consistency and portability.</p><h3>3. Config</h3><p>An app’s config includes anything likely to vary between deploys, such as database URLs, API keys, and deployment-specific values. config settings should be stored separately from the codebase.</p><p>Storing them as constants in the code is discouraged, configs should instead be stored as environment variables inside a .env file, which is not managed by your version control (gitignore this file if it lives in the same folder as your project).</p><p>In Python, configs can be managed using the os.environ module to access and set environment variables inside the env file. The <a href="https://pypi.org/project/python-decouple/">python-decouple</a> library simplifies things even further.</p><p>Env vars should be granular and independent, avoiding grouping them into “environments” as done in frameworks like Rails.</p><h3>4. Backing services</h3><p>Backing services encompass various services accessed over the network, such as databases (e.g., MySQL), messaging systems (e.g., RabbitMQ), or cloud services (e.g., Amazon S3).</p><p>Backing services should be treated as attached resources, whether they are managed locally or by third parties: The distinction between locally managed and third-party services is irrelevant to the application code, which interacts with both types via URLs or credentials stored in the configuration.</p><p>The codebase of a twelve-factor app remains agnostic to the origin of the backing services. This means that, for example, swapping a local MySQL database with a third-party service like Amazon RDS or replacing a local SMTP server with a service like Postmark can be accomplished without modifying the application’s code. Only the config, containing the locator/credentials of the services, needs to be updated.</p><h3>5. Build, release, run.</h3><p>it’s essential to strictly separate the build, release, and run stages in the deployment process.</p><ol><li>Build Stage: transforms the code repository into an executable bundle, fetching vendor dependencies and compiling binaries and assets. This stage may involve tasks like installing dependencies specified in requirements.txt using pip and compiling static assets if applicable.</li><li>Release Stage: the build produced by the build stage is combined with the deployment’s current config. The resulting release contains both the build and the configuration and is prepared for immediate execution in the execution environment. Ensure that each release has a unique release ID, typically a timestamp or an incrementing number, and is immutable once created.</li><li>Run Stage: Also known as runtime, this stage involves running the application in the execution environment by launching the app’s processes against a selected release. While the build and release stages are typically initiated by developers during deployment, the run stage may occur automatically, such as during a server reboot or when a crashed process is restarted by the process manager.</li></ol><p>You should aim to keep the run stage as simple as possible to minimize potential issues that could arise when the app is running in production. This is because runtime errors can occur unexpectedly, especially when no developers are available to address them. In contrast, the build stage can be more complex, as any errors are immediately visible to you the developer driving the deployment process.</p><p>Your deployment tool typically offers release management features, such as the ability to roll back to a previous release.</p><h3>6. Processes.</h3><p>Execute your app as one or more stateless processes. This means that each process should not rely on or maintain any persistent state locally. Instead, any data requiring persistence should be stored in a stateful backing service like a database.</p><p>Python applications should avoid relying on local memory or filesystem for storing data across requests or jobs. While temporary usage of memory or filesystem for caching purposes is acceptable within the scope of a single transaction, it should not be assumed that this data will be available in subsequent requests or jobs, especially considering the possibility of multiple processes handling requests concurrently.</p><p>Asset compilation, such as in Django applications using Django-asset-packager, should ideally be performed during the build stage rather than relying on filesystem caching. Similarly, you should refrain from using “sticky sessions” where user session data is cached in memory and expect future requests from that same user to be routed to the same process. This violates the statelessness principle of twelve-factor apps. Instead, session state data should be stored in a datastore with time-expiration features, such as Memcached or Redis.</p><h3>7. Port binding</h3><p>Your app should not rely on the runtime injection of a web server. Instead, it should export its service over HTTP by binding to a port and listening for requests. During development, access is usually through a local URL, while in deployment, a routing layer forwards requests to the port-bound web processes. This is typically achieved by integrating a web server library like Tornado for Python directly into the app’s codebase.</p><p>Port binding isn’t limited to HTTP; other server software can also be run by binding to a port, a good example is Redis, which speaks the Redis protocol but is accessed by your app via HTTP.</p><p>Note that the port-binding approach means that one app can become the backing service for another app, by providing the URL to the backing app as a resource handle in the config for the consuming app.</p><h3>8. Concurrency</h3><p>Processes are first-class citizens and should be the way you plan your scaling. Drawing inspiration from the Unix process model, You should assign different types of work to specific process types, for example, handling HTTP requests to web processes and background tasks to worker processes. Since your app shares nothing with another, and is therefore horizontally partitionable, adding more concurrency is a simple and reliable operation. Imagine the scaling advantages this affords.</p><p>Processes in a twelve-factor app should not daemonize or write PID files. Instead, they should rely on the operating system’s process manager or tools like systemd, a distributed process manager, for managing output streams, handling crashed processes, and managing restarts and shutdowns initiated by users. This ensures a streamlined and reliable process management strategy.</p><h3>9. Disposability</h3><p>The twelve-factor app emphasizes disposable processes that start up quickly, shut down gracefully, and are robust against sudden failures. This facilitates rapid scaling, deployment, and robustness in production environments.</p><ol><li>Fast Startup: Processes aim to minimize startup time, ideally taking only a few seconds to become operational. This agility aids in release processes and scaling up, while also enhancing robustness by enabling quick migration to new physical machines.</li><li>Graceful Shutdown: Processes respond to SIGTERM signals by ceasing to listen on service ports, allowing ongoing requests to finish, and then exiting. This ensures smooth transitions without disrupting ongoing operations.</li><li>Robustness: Processes are designed to handle sudden failures, such as hardware failures, by relying on robust queueing backends like Beanstalkd that return jobs to the queue upon disconnection or timeout. This ensures the application can handle unexpected terminations and follows a crash-only design philosophy for resilience.</li></ol><p>For web processes, graceful shutdown involves stopping to accept new requests while allowing existing ones to complete. This assumes short-lived HTTP requests or seamless reconnection for long-polling scenarios. Worker processes gracefully shut down by returning current jobs to the work queue, ensuring no work is lost. This may involve mechanisms like sending a NACK in RabbitMQ or an automatic job return in Beanstalkd.</p><h3>10. Dev/Prod parity.</h3><p>The twelve-factor app should aim to minimize gaps between development, staging, and production environments to enable continuous deployment. This involves:</p><ol><li>Time Gap Reduction: Developers aim to deploy code within hours or even minutes of writing it, instead of waiting weeks as in traditional approaches.</li><li>Personnel Gap Reduction: Developers involved in writing code are closely engaged in deploying and monitoring it in production, unlike traditional setups where separate operations teams handle deployment.</li><li>Tools Gap Reduction: Development and production environments are kept as similar as possible to minimize differences in tools and configurations, enhancing reliability and easing deployment.</li><li>Back-end Services Parity: Developers use the same backing services (e.g., databases, queues, caches) in development, staging, and production to avoid compatibility issues. Resist the urge to use lightweight local services, modern packaging systems and provisioning tools make it feasible to run production-like environments locally.</li><li>Resistance to Different Backing Services: Developers should resist the temptation to use different backing services between environments, as even with adapters, tiny incompatibilities can cause deployment issues, discouraging continuous deployment.</li><li>Use of Adapters: While adapters to different backing services remain useful for portability, all environments should use the same type and version of each backing service to maintain consistency and facilitate deployment.</li></ol><p>Overall, the goal is to align development practices closely with production environments to enable seamless and rapid deployment while minimizing friction and errors.</p><h3>11. Logs</h3><p>Logs are time-ordered events collected from all running processes and services. They are typically in a text format, with each event represented as a line.</p><p>A twelve-factor app does not concern itself with the routing nor the storage of log files, Instead, each process writes its event stream, unbuffered, to stdout. In a development environment, developers observe the stream in the terminal to understand the app’s behavior.</p><p>In staging or production environments, the execution environment captures and gathers the event streams from all processes, which are then routed to one or more final destinations for viewing and archival.</p><p>The Archival destinations should be managed entirely by the execution environment; they should not be visible or configurable by the app itself.</p><h3>12. Admin processes</h3><p>Administrative tasks typically include activities like running database migrations, running a console (say to inspect an app’s models), or executing one-time scripts.</p><p>To ensure consistency and reliability, one-off admin processes should run in an environment identical to the regular processes of the application. This means they utilize the same codebase and configuration. Admin code should ship alongside application code to prevent synchronization issues.</p><p>Dependency isolation techniques should be applied consistently across all process types. For instance, if the web process starts with gunicorn, then running database migrations should use the same environment and dependencies.</p><p>Python’s support for <a href="https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop">REPL</a> shells (e.g., through the python command) and ease of running one-off scripts make it well-suited for Twelve-Factor development. In a local deployment environment, developers typically execute admin processes directly from the application&#39;s directory. In production, developers can leverage SSH or other remote command execution mechanisms to run such processes securely.</p><h3>Conclusion.</h3><p>Following the guidelines of the twelve-factor app will save you a lot of headaches, especially in scaling, and by scaling I mean the team, the codebase, and in production.</p><p>Happy coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae631dca450a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2 lessons for Python developers from the world of Rust.]]></title>
            <link>https://medium.com/@orichcaspertheghost/2-lessons-for-python-developers-from-the-world-of-rust-33baaa264513?source=rss-4c803599bd94------2</link>
            <guid isPermaLink="false">https://medium.com/p/33baaa264513</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[inheritance]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[oop]]></category>
            <dc:creator><![CDATA[casper orich]]></dc:creator>
            <pubDate>Mon, 26 Feb 2024 11:37:22 GMT</pubDate>
            <atom:updated>2024-02-26T12:12:38.849Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CSgVTYIfW3IVENik" /><figcaption>Photo by <a href="https://unsplash.com/@jack_1?utm_source=medium&amp;utm_medium=referral">Rémi Jacquaint</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As Pythonistas, we love Python and swear by it. We love it for many reasons, including but not limited to its flexibility and unbeatable readability. But that should not squash our adventurous spirit. Recently, my curiosity has taken me to the weird but wonderful world of Rust, and I have returned home with a few lessons that I want to share with you.</p><h3>Lesson 1: Mutability</h3><p>In Python, you don’t think too much about mutability, and that is by design. Rust, however, forces you to think about the mutability of your variables. Take an example:</p><pre>fn main() {<br>    let a = 1;<br>    println!(&quot;The value of a is: {a}&quot;);<br>    a = 2;<br>    println!(&quot;The value of a is: {a}&quot;);<br>}</pre><p>Don&#39;t panic Pythonistas, this is a Rust snippet, which explains the semicolons and fn keyword instead of def. But it reads rather like Python. The variable a is being updated from 1 to 2. While a similarly-syntaxed code in Python would run, this Rust snippet would not compile ( Rust is a <a href="https://byjus.com/gate/difference-between-compiled-and-interpreted-language/#:~:text=A%20compiled%20language%20is%20converted,a%20program%20into%20machine%20language.&amp;text=The%20compiled%20programs%20run%20faster%20than%20interpreted%20programs.">compiled</a> language ). This is because variables in Rust by default are immutable and it expects you to explicitly state if they are not. Therefore for the snippet above to compile, you would need to do this:</p><pre>fn main() {<br>    // use the mut keyword<br>    let mut a = 1;<br>    println!(&quot;The value of a is: {a}&quot;);<br>    a = 2;<br>    println!(&quot;The value of a is: {a}&quot;);<br>}</pre><p>Notice the mut keyword. This tells the compiler that it is okay for the value of a to change later in the program.</p><h4>Python variables too are immutable (Some of them)</h4><p>Python variables, including primitives like integers, floats, booleans, and strings; and complex types like frozen sets are immutable. Operations that appear to modify their values in the actual sense create a new object with the modified value.</p><pre>a = 1<br>a = 2 # a is a new object created to store the modified value of a<br>print(a) # 2</pre><p>You can confirm this by printing out the unique ID representing the memory address where the object is stored.</p><pre>a = 1<br>print(id(a)) # 139755038851312<br>a = 2<br>print(id(a)) # 139755038851344<br><br>print(a)</pre><p>You should get unique values from the two id() function calls, confirming that they do not point to the same address.</p><h4>A concept called shadowing.</h4><p>In Python, when you reassign a variable, you are creating a new object and binding it to the same variable name. The previous object is unaffected and may be garbage collected if there are no other references to it. This process is akin to a concept called shadowing in Rust, where a new variable with the same name is created, shadowing the previous one. Albeit with differences in how they are implemented and used.</p><pre>fn main() {<br>    let a = 1;<br>    println!(&quot;The value of a is: {a}&quot;);<br>    let a = 2;<br>    println!(&quot;The value of a is: {a}&quot;);<br>}</pre><p>Using the let keyword, you can ‘shadow’ a with a new value.</p><h4>Understanding the stack and heap.</h4><p>Shadowing can be useful to maintain clarity in code by avoiding unnecessary new variable declarations. Beyond that, The world of Rust teaches us to be intentional about the mutability of our variables. We should always consider whether and how they will mutate throughout the program.</p><p>A common pitfall occurs when passing mutable objects as arguments to functions and inadvertently modifying them within the function.</p><pre>def modify_list(lst):<br>    lst.append(4)<br>    lst = [1, 2, 3]  # Reassigning lst to a new list<br><br>my_list = [1, 2, 3]<br>modify_list(my_list)<br>print(my_list)  # Output: [1, 2, 3, 4]</pre><p>In this example, the modify_list function appends 4 to the existing list lst, which modifies the original list passed to the function. However, when lst is reassigned to a new list [1, 2, 3] within the function, it only affects the local scope of the function. The original list my_list remains unchanged outside the function.</p><p>This behavior might be unexpected to someone who assumes that modifying lst within the function would affect my_list outside of the function as well.</p><p>Let us understand what is going on here in detail:</p><p>When you pass a list as an argument to a function in Python ( or any other mutable type ), what’s passed is a reference to the list object, not a copy of the list itself. This behavior is due to how Python handles variables and objects in memory and is related to the concepts of call stacks and heaps.</p><p>In oversimplified terms:</p><ul><li><strong>Stack</strong>: A region of memory that keeps track of function calls and local variables. A function stack stores a copy of the values of the primitive types (immutable types) passed in as arguments and <strong>only the references</strong> to the more complex (and sometimes mutable) types passed in as arguments.</li><li><strong>Heap</strong>: The heap is a region of memory where complex objects are stored. e.g. lists, dictionaries, and custom objects are stored in the heap.</li></ul><p>When you pass a list in as an argument to a function:</p><ol><li>The reference to the list object is pushed onto the stack as part of the function call.</li><li>The function receives this reference as a parameter and can access the list object through it.</li><li>Any modifications made to the list object inside the function are reflected in the original list because both the function’s parameter and the original list variable reference the same object in memory.</li></ol><p>This behavior is different from passing immutable objects like integers or strings, where a copy of the value is passed to the function.</p><p>In short, modifying the mutable type (list) inside the function modifies the list outside the function. The function and the lst variable points to the same location as my_list.</p><p>The modify_list() function can be corrected by making a copy of the list inside the function, that way you are not modifying the original list (my_list) that is outside its scope, essentially turning it into a <a href="https://www.studysmarter.co.uk/explanations/computer-science/functional-programming/pure-function/#:~:text=In%20Python%2C%20a%20pure%20function,solely%20on%20its%20input%20arguments.">pure function</a>. You could then return the modified list as the function’s return value as shown below:</p><pre>def modify_list(lst):   <br>    lst = lst[:] # a copy of lst is created, change to this does not affect the original<br>    lst.append(4)    <br>    lst = [1, 2, 3]  # Reassigning lst to a new list    <br>    return lst<br><br><br>my_list = [1, 2, 3]<br>my_list = modify_list(my_list)<br>print(my_list)  # Output: [1, 2, 3]</pre><p>If you are keen on modifying the list <a href="https://en.wikipedia.org/wiki/In-place_algorithm#:~:text=More%20broadly%2C%20in%2Dplace%20means,o(n)%20is%20allowed.">in place</a>( for memory performance reasons etc.), avoid doing any reassignment within the function, and make sure every operation is in place. Example:</p><pre>def modify_list(lst):       <br>    lst.append(4)      # in-place append<br>    lst.clear()        # in-place clear<br>    lst += [1, 2, 3]   # in-place append   <br><br><br>my_list = [1, 2, 1]<br>modify_list(my_list)<br>print(my_list)  # Output: [1, 2, 3]</pre><p>Another common pitfall you could study would be the <a href="https://stackoverflow.com/questions/41686829/why-does-pycharm-warn-about-mutable-default-arguments-how-can-i-work-around-the">mutable default argument</a> problem.</p><p>This goes to show you that understanding the ins and outs of mutability in Python is vital to writing readable and reliable code. Since Rust is very opinionated on this, it forces Rustaceans (as they are called ) to always think about this concept. It is up to us Pythonistas to keep this in mind.</p><h3>Lesson 2: OOP, What is it?</h3><p>As part of its <a href="https://doc.rust-lang.org/book/ch17-01-what-is-oo.html">docs</a> (I highly recommend you read this part), Rust takes a moment to identify where it stands on matters OOP, acknowledging the lack of a consensus in the programming community about what features a language must have to be considered object-oriented. On the three key features generally associated with OOP, here is where Rust stands in comparison to Python and why you should care.</p><h4>Objects</h4><blockquote>Object-oriented programs are made up of objects. An <em>object</em> packages both data and the procedures that operate on that data. The procedures are typically called <em>methods</em> or <em>operations</em>. ~ The book <em>Design Patterns: Elements of Reusable Object-Oriented Software</em> by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (Addison-Wesley Professional, 1994)</blockquote><p>With this definition, Rust is object-oriented: There are constructs called structs and enums that have data, and impl blocks that provide methods on structs and enums. Even though they are not strictly called objects in Rust, they do exactly what the textbook definition of objects does.</p><pre>struct Rectangle {<br>    width: u32,<br>    height: u32,<br>}<br><br>impl Rectangle {<br>    fn area(&amp;self) -&gt; u32 {<br>        self.width * self.height<br>    }<br>}<br><br>fn main() {<br>    let rect = Rectangle { width: 10, height: 20 };<br>    println!(&quot;Area of rectangle: {}&quot;, rect.area());<br>}</pre><p>In Rust, it’s common to define small, focused structs that represent data, and then define separate impl blocks that provide behavior for those structs. This makes it easy to reuse data structures and mix and match behavior as needed.</p><p>Rust favors this approach (Separating data from methods during declaration ) because it affords a cleaner and clearer code structure that can lead to more maintainable code. The same can be achieved in Python as shown below:</p><pre>from dataclasses import dataclass<br><br>@dataclass<br>class Rectangle:<br>    width: int<br>    height: int<br><br># Function to calculate the area of a rectangle<br>def area(rect: Rectangle) -&gt; int:<br>    return rect.width * rect.height<br><br># Example usage<br>rect = Rectangle(10, 20)<br>print(&quot;Area of rectangle:&quot;, area(rect))</pre><p>I used a dataclass because it lends itself to this sort of construct, They are designed to hold only data values and typically do not have any methods. The area function is defined separately outside the Rectangle class. This function takes a Rectangle instance as its argument and calculates the area using the width and height attributes of the rectangle.</p><p>Separating the calculation of the area into a standalone function keeps the Rectangle class focused on representing data, adhering to the principle of single responsibility ( and separation of concerns ).</p><p>Rust’s struct and impl blocks lend themselves well to composition because they allow you to define small, focused data structures (structs) and then define behavior (methods) separately using impl blocks. This separation of concerns makes it easy to compose complex functionality by combining smaller building blocks.</p><p>Consider that you wanted to create a colored rectangle:</p><pre>// Define another struct representing a colored rectangle<br>struct ColoredRectangle {<br>    rectangle: Rectangle,<br>    color: String,<br>}<br><br>// Implement methods for the ColoredRectangle struct<br>impl ColoredRectangle {<br>    // Method to get the area of the colored rectangle<br>    fn area(&amp;self) -&gt; u32 {<br>        self.rectangle.area()<br>    }<br><br>    // Method to get the color of the rectangle<br>    fn get_color(&amp;self) -&gt; &amp;str {<br>        &amp;self.color<br>    }<br>}<br><br>fn main() {<br>    // Create a new colored rectangle<br>    let colored_rect = ColoredRectangle {<br>        rectangle: Rectangle { width: 10, height: 5 },<br>        color: String::from(&quot;blue&quot;),<br>    };<br><br>    // Call methods on the colored rectangle<br>    println!(&quot;Area: {}&quot;, colored_rect.area());<br>    println!(&quot;Color: {}&quot;, colored_rect.get_color());<br>}</pre><p>The same can be achieved in Python as shown below:</p><pre>from dataclasses import dataclass<br><br>@dataclass<br>class Rectangle:<br>    width: int<br>    height: int<br><br>@dataclass<br>class ColoredRectangle:<br>    rectangle: Rectangle<br>    color: str<br><br><br># Function to calculate the area of a rectangle<br>def area(rect: Rectangle) -&gt; int:<br>    return rect.width * rect.height<br><br>def color(rect: ColoredRectangle) -&gt; str:<br>    return rect.color<br><br># Example usage<br>rect = Rectangle(10, 20)<br>colored_rect = ColoredRectangle(rectangle=rect,color=&quot;blue&quot;)<br>print(&quot;Area of rectangle:&quot;, area(rect))<br>print(&quot;Color of rectangle: &quot;, colored_rect.color)py</pre><p>The ColoredRectangle class is ‘composed’ of an instance of the Rectangle class and a color attribute.</p><h4>Encapsulation</h4><p>Encapsulation ensures that the implementation details of an object are hidden from the outside world, allowing access only through a well-defined public interface. This restricts direct access to an object’s internals, preventing external code from modifying its state or behavior directly. Rust achieves this through the pub keyword to decide which methods should be public. By default, everything else is private.</p><pre>pub struct Counter {<br>    count: u32,<br>}<br><br>impl Counter {<br>    // Public method to increment the counter<br>    pub fn increment(&amp;mut self) {<br>        self.count += 1;<br>    }<br><br>    // Public method to get the current value of the counter<br>    pub fn get_count(&amp;self) -&gt; u32 {<br>        self.count<br>    }<br><br>    // Private method to reset the counter to zero<br>    fn reset(&amp;mut self) {<br>        self.count = 0;<br>    }<br><br>    // Public method to reset the counter to zero from within the struct<br>    pub fn reset_counter(&amp;mut self) {<br>        self.reset();<br>    }<br>}<br><br>fn main() {<br>    // Create a new counter<br>    let mut counter = Counter {count: 0};<br><br>    // Increment the counter<br>    counter.increment();<br>    counter.increment();<br><br>    // Access the current count<br>    println!(&quot;Current count: {}&quot;, counter.get_count());<br><br>    // Reset the counter using the public method<br>    counter.reset();<br><br>    // Reset the counter using the public method<br>    counter.reset_counter();<br><br>    // Access the count after resetting<br>    println!(&quot;Count after reset: {}&quot;, counter.get_count());<br>}  </pre><p>Python takes a different approach, by default all methods are public. If you need to create a private method, you prefix the method name with the double underscore “__”. Behind the scenes, a method identifier in the form __method_name() is replaced with _classname__method_name (mangling) where classname is the class name with a leading underscore.</p><pre>class Counter:<br>    def __init__(self):<br>        self.__count = 0<br><br>    # Public method to increment the counter<br>    def increment(self):<br>        self.__count += 1<br><br>    # Public method to get the current value of the counter<br>    def get_count(self):<br>        return self.__count<br><br>    # Private method to reset the counter to zero<br>    def __reset(self):<br>        self.__count = 0<br><br>    # Public method to reset the counter to zero from within the class<br>    def reset_counter(self):<br>        self.__reset()<br><br>def main():<br>    # Create a new counter<br>    counter = Counter()<br><br>    # Increment the counter<br>    counter.increment()<br>    counter.increment()<br><br>    # Access the current count<br>    print(&quot;Current count:&quot;, counter.get_count())<br><br>    # Reset the counter using the public method<br>    counter.__reset()  # Note: This will not work due to name mangling<br><br>    # Reset the counter using the public method<br>    counter.reset_counter()<br><br>    # Access the count after resetting<br>    print(&quot;Count after reset:&quot;, counter.get_count())<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h4>Inheritance</h4><p>Inheritance is when a new class, called a derived class or subclass, is created from an existing class, called a base class or superclass. The derived class inherits attributes and methods from the base class, allowing for code reuse and promoting modularity and extensibility in software design.</p><p>If a language must have inheritance to be considered OOP, then Rust isn&#39;t OOP. There is no way to define a struct that inherits the parent struct’s fields and method implementations without using a macro.</p><p>Why do you need inheritance? It&#39;s mostly one of two reasons:</p><ul><li><strong>Code reuse</strong>: Define a method for one type and then use this implementation for another type</li><li><strong>Polymorphism</strong>: You want to be able to substitute multiple objects for each other at runtime if they share certain characteristics.</li></ul><p>Rust clarifies that polymorphism is not intrinsically tied to inheritance:</p><blockquote>To many people, polymorphism is synonymous with inheritance. But it’s actually a more general concept that refers to code that can work with data of multiple types. For inheritance, those types are generally subclasses<em>.</em></blockquote><p>You can achieve code reuse in Rust using default trait method implementations. A trait in Rust is a construct that defines a set of methods that types can implement.</p><pre>trait Move {<br>    // Define a method move_forward with a default implementation<br>    fn move_forward(&amp;self){<br>        println!(&quot;Just move&quot;);<br>    }<br>}<br><br>// Define a struct named Car<br>struct Car;<br>// Implement the Move trait for the Car struct<br>impl Move for Car{}<br><br>fn main() {<br>    let car = Car;<br>    car.move_forward();       // Output: Just move.<br>}</pre><p>Every type that implements the move trait will have access to its default implementation without having to write any further code (code reuse). This is similar to a parent class having an implementation of a method and an inheriting child class also having the implementation of the method. It is also possible to override the default implementation:</p><pre>trait Move {<br>    fn move_forward(&amp;self){<br>        println!(&quot;Just move&quot;);<br>    }<br>}<br><br>struct Car;<br>struct Bicycle;<br>struct Motorcycle;<br><br>// override move_foward<br>impl Move for Car {<br>    fn move_forward(&amp;self) {<br>        println!(&quot;Car is driving forward.&quot;);<br>    }<br>}<br>// override move_foward<br>impl Move for Bicycle {<br>    fn move_forward(&amp;self) {<br>        println!(&quot;Bicycle is pedaling forward.&quot;);<br>    }<br>}<br><br>// use default implementation<br>impl Move for Motorcycle {}<br><br><br><br>fn main() {<br>    let car = Car;<br>    let bicycle = Bicycle;<br>    let motorcycle = Motorcycle;<br><br>    car.move_forward();       // Output: Car is driving forward.<br>    bicycle.move_forward();   // Output: Bicycle is pedaling forward.<br>    motorcycle.move_forward();// Output: Just move.<br>}</pre><p>On polymorphism:</p><blockquote>Rust uses generics to abstract over different possible types and trait bounds to impose constraints on what those types must provide. This is sometimes called <em>bounded parametric polymorphism</em>. ~ <a href="https://doc.rust-lang.org/book/ch17-01-what-is-oo.html">https://doc.rust-lang.org/book/ch17-01-what-is-oo.html</a></blockquote><p>The takeaway here is that code reuse and polymorphism are not tied to inheritance, they are wide concepts with different ways to achieve them. Consider how you could achieve polymorphism in Python using Duck typing. Duck typing is a concept that revolves around an object’s behavior rather than its class or type. This means you’re more interested in what an object can do (i.e., the methods it has), rather than what it is (i.e., its class or type). If an object “walks like a duck and quacks like a duck,” then it’s treated as a duck.</p><pre>class Car:<br>    def move_forward(self):<br>        print(&quot;Car is driving forward.&quot;)<br><br>class Bicycle:<br>    def move_forward(self):<br>        print(&quot;Bicycle is pedaling forward.&quot;)<br><br>class Motorcycle:<br>   <br>    def move_forward(self):<br>        print(&quot;Motorcycle is accelerating forward.&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br><br>    def move_anything_forward(obj):<br>        if hasattr(obj,&#39;move_forward&#39;):<br>            obj.move_forward()<br>        else:<br>            print(f&quot;{obj} has no move_foward method&quot;)<br><br>    # Creating instances of different classes<br>    car = Car()<br>    bicycle = Bicycle()<br>    motorcycle = Motorcycle()<br><br><br>    # Using the move_anything_forward function with different objects<br>    move_anything_forward(car)        # Output: Car is driving forward.<br>    move_anything_forward(bicycle)    # Output: Bicycle is pedaling forward.<br>    move_anything_forward(motorcycle)# Output: Motorcycle is accelerating forward.</pre><p>In this case, you do not care what type of car, bicycle, or motorcycle is, as long as they have the move_foward method, they can be substituted for another, achieving polymorphism without having to create subclasses.</p><p>Polymorphism, in general, refers to the ability of different types to be treated uniformly under a common interface. What we have discussed so far can be said to be three different subsets of polymorphisms:</p><ol><li><strong>Subtype Polymorphism</strong> (also known as inheritance-based polymorphism): This occurs when a subclass can be treated as its superclass. It allows a variable of a superclass type to reference a subclass object, and the methods called on that variable will execute the subclass’s implementation if overridden.</li><li><strong>Parametric Polymorphism </strong>(also known as generics): This allows functions and data types to operate on values of various types, without any loss of type safety. It’s achieved through the use of generic type parameters.</li><li><strong>Duck Typing Polymorphism</strong>: This is a style of typing in which an object’s suitability for a particular behavior is determined by the presence of certain methods and properties, rather than the object’s actual type or inheritance hierarchy. If an object “walks like a duck and quacks like a duck,” then it’s treated as a duck. This is a characteristic of dynamically typed languages where types are inferred at runtime.</li></ol><h3>Conclusion</h3><p>Embracing new languages and exploring different paradigms can enrich our understanding of programming and ultimately make us better developers. While Python remains a beloved tool in our arsenal, venturing into the realm of Rust has offered valuable insights and lessons. Rust challenges us to think differently and pushes the boundaries of what we can achieve. So let us continue to embrace curiosity, venture into the unknown, and bring back lessons that will further enhance our craft as Pythonistas. After all, in the ever-evolving landscape of technology, staying stagnant is not an option.</p><p>Happy coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33baaa264513" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python’s with statement: Beyond just opening and closing files.]]></title>
            <link>https://medium.com/@orichcaspertheghost/pythons-with-statement-beyond-just-opening-and-closing-files-f9edf368a3be?source=rss-4c803599bd94------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9edf368a3be</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[casper orich]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 08:32:16 GMT</pubDate>
            <atom:updated>2024-02-05T08:32:16.383Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jVXn9QfDffDH9om7AFP7LA.jpeg" /></figure><p>If you have ever done any file manipulations, then you are probably familiar with Python’s with statement.</p><pre>with open(&quot;hello.txt&quot;, mode=&quot;w&quot;) as file:<br>    file.write(&quot;Hello, World!&quot;)</pre><p>This allows you to do manipulations on the file while guaranteeing that the file will be closed in the end. You have probably used this statement before, maybe copied from StackOverflow — no shame 😃, but have never given much thought to how and why this works. Well, in this article, I am going to demystify that. In the end, you will learn how to use the with statement in ways other than opening and closing files, and adding another tool to your Python toolbelt.</p><h3>Context managers.</h3><p>The Python with statement works with a construct called a <strong>context manager.</strong> Evaluating the with statement creates a <strong>runtime context </strong>that is defined and controlled by the context manager.</p><pre>with expression as target_var:<br>    do_something(target_var)</pre><p>Therefore, by evaluating the with statement, an instance is returned (and assigned to target_var ) which has implemented the <strong>context management protocol</strong> with two special methods:</p><ul><li>__enter__() :Called to enter the runtime context. This is where the setup code typically lives (e.g. opening files), its return value is bound to target_var if provided.</li><li>__exit__() : Called when it is time to exit the runtime context. This is where teardown code typically lives (e.g. closing files)</li></ul><p>Notice that you can only use the with statement with objects that support the context management protocol. For example, when you run with open(&quot;hello.txt&quot;, mode=&quot;w&quot;) as file:open() returns an io.TextIOBase object, which implements the context manager protocol.</p><p>The two methods make the with statement such a powerful tool, especially for acquiring and releasing resources. The alternative would be to use the try … finally construct.</p><pre># Safely open the file<br>file = open(&quot;hello.txt&quot;, &quot;w&quot;)<br><br>try:<br>    file.write(&quot;Hello, World!&quot;)<br>except Exception as e:<br>    print(f&quot;An error occurred while writing to the file: {e}&quot;)<br>finally:<br>    # Make sure to close the file after using it<br>    file.close()</pre><p>But it is clear which one is the cleaner, more readable, and reusable approach.</p><h3>Custom context managers.</h3><p>The file open() function can be used with the with statement because it returns an object that implements the context management protocol. The good news is that you too can achieve the same functionality by implementing the context management protocol yourself.</p><p>When is it appropriate to use context managers?</p><blockquote>Whenever you want to <strong>REUSE</strong> <strong>setup and teardown code</strong>, i.e, some code runs before and another after an operation, that is a candidate for context managers.</blockquote><p>Examples:</p><ul><li>Open and close</li><li>Lock and release</li><li>Change and reset</li><li>Create and delete</li><li>Enter and exit</li><li>Start and stop</li></ul><p>There are two approaches to context managers, class-based and function-based:</p><h4>Class-based context managers</h4><p>These are pretty straightforward, all you need to do is provide the __enter__() and __exit__() methods to a class.</p><p>Consider the example below. This code runs a spaceship (believe it or not), and the information about the planets is stored inside the PLANET_INFO dictionary, while the units of fuel consumed to leave a planet are predicted by dividing the UNITS_CONSUMED_TO_LEAVE_JUPITER (which is known to be 20) by the planet’s size in km³.</p><pre>PLANET_INFO = {<br>    &quot;Mercury&quot;: {&quot;moons&quot;: 0, &quot;position_from_sun&quot;: 1, &quot;vol_km3&quot;: 6.083e10},<br>    &quot;Venus&quot;: {&quot;moons&quot;: 0, &quot;position_from_sun&quot;: 2, &quot;vol_km3&quot;: 9.2843e11},<br>    &quot;Earth&quot;: {&quot;moons&quot;: 1, &quot;position_from_sun&quot;: 3, &quot;vol_km3&quot;: 1.08321e12},<br>    &quot;Mars&quot;: {&quot;moons&quot;: 2, &quot;position_from_sun&quot;: 4, &quot;vol_km3&quot;: 1.6318e11},<br>    &quot;Jupiter&quot;: {&quot;moons&quot;: 79, &quot;position_from_sun&quot;: 5, &quot;vol_km3&quot;: 1.43128e15},<br>    &quot;Saturn&quot;: {&quot;moons&quot;: 83, &quot;position_from_sun&quot;: 6, &quot;vol_km3&quot;: 8.2713e14},<br>    &quot;Uranus&quot;: {&quot;moons&quot;: 27, &quot;position_from_sun&quot;: 7, &quot;vol_km3&quot;: 6.833e13},<br>    &quot;Neptune&quot;: {&quot;moons&quot;: 14, &quot;position_from_sun&quot;: 8, &quot;vol_km3&quot;: 6.254e13}<br>}<br>UNITS_CONSUMED_TO_LEAVE_JUPITER = 20<br>FUEL_CONSUMPTION_RATE = UNITS_CONSUMED_TO_LEAVE_JUPITER / PLANET_INFO[&#39;Jupiter&#39;][&#39;vol_km3&#39;]  # Adjusted for illustration</pre><p>Create a context manager that will tell the information on a planet upon entering it and tell how much fuel will be spent leaving it.</p><pre><br>class PlanetContextManager:<br><br>    def __init__(self,planet,fuel):<br>        self.planet = planet<br>        self.fuel = fuel<br><br>    def __enter__(self):<br>        print(f&quot;Entering the {self.planet} context...&quot;)   <br>        # return the planet&#39;s info.<br>        return PLANET_INFO[self.planet]<br>    <br>    def __exit__(self, exc_type, exc_value, exc_tb):       <br>        #calculate fuel spent leaving the planet<br>        self.fuel = self.fuel - (PLANET_INFO[self.planet][&#39;vol_km3&#39;] * FUEL_CONSUMPTION_RATE)<br>        print(f&quot;Leaving {self.planet}...You will have {self.fuel} units of fuel left&quot;)<br><br>        print(exc_type, exc_value, exc_tb, sep=&quot;\n&quot;)<br></pre><p>Here, the context manager’s __enter__() method gets the info about the planet you enter and returns its value, and the __exit__() method calculates the units of fuel that will be spent leaving the planet. This context manager can be used with the with statement as follows:</p><pre>with PlanetContextManager(&quot;Earth&quot;,100) as planet:<br>    print(planet)<br><br># Entering the Earth context...<br># {&#39;moons&#39;: 1, &#39;position_from_sun&#39;: 3, &#39;vol_km3&#39;: 1083210000000.0}<br># Leaving Earth...You will have 99.98486375831423 units of fuel left<br># None<br># None<br># None</pre><p>Take note of the __exit__() function’s arguments, exc_type, exc_value, and exc_tb .They are passed in when an exception occurs inside the runtime context. The exception type, value, and traceback information are passed in respectively. From the above code, their values are set to None since no exception occurs within the context. Try accessing the planet&#39;s distance from the sun, a value not existing in the planet info dictionary.</p><pre>with PlanetContextManager(&quot;Jupiter&quot;,100) as planet:<br>    print(planet)<br>    print(planet[&#39;distance_from_sun&#39;])</pre><pre>Entering the Jupiter context...<br>{&#39;moons&#39;: 79, &#39;position_from_sun&#39;: 5, &#39;vol_km3&#39;: 1431280000000000.0}<br>&lt;class &#39;KeyError&#39;&gt;<br>&#39;distance_from_sun&#39;<br>&lt;traceback object at 0x7fbc3a9596c0&gt;<br>Traceback (most recent call last):<br>  File &quot;/home/casper/blog/context_managers/class_based.py&quot;, line 30, in &lt;module&gt;<br>    print(planet[&#39;distance_from_sun&#39;])<br>KeyError: &#39;distance_from_sun&#39;</pre><h4>Function-based context managers.</h4><p>An alternative way to write context managers is to use <a href="https://book.pythontips.com/en/latest/generators.htm">Python’s generator functions </a>and the <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager">contextlib.contextmanager </a>decorator. It is intuitive and has the advantage of having less boilerplate code. This is how you would write the same spaceship code using functions:</p><pre>from contextlib import contextmanager<br><br>...<br><br>@contextmanager<br>def planet_context_manager(planet,fuel):<br>    print(f&quot;Entering the {planet} context...&quot;) <br>       <br>    yield PLANET_INFO[planet]<br><br>    fuel = fuel - (PLANET_INFO[planet][&#39;vol_km3&#39;] * FUEL_CONSUMPTION_RATE)<br>    print(f&quot;Leaving {planet}...You will have {fuel} units of fuel left&quot;)</pre><p>The setup section is written before the yield statement, the yield statement yields control for the code inside the context to execute, and it can return an object that can then be assigned to target_variable if provided, using a function-based context manager is similar to the class-based variant.</p><pre>with planet_context_manager(&quot;Jupiter&quot;,100) as planet:<br>    print(planet)    </pre><h3>Use cases</h3><p>Now that you understand the concept of context managers and the with statement, let us look at examples of how you can use them to your advantage.</p><h4>Clever APIs for your classes.</h4><p>Imagine creating a to-do app that handles tasks.</p><pre>from abc import ABC,abstractmethod<br>import time<br><br><br>class TaskADT(ABC):<br>    @abstractmethod<br>    def execute():<br>        pass<br><br>class Task(TaskADT):<br>    def __init__(self, name):<br>        self.name = name<br><br>    def execute(self):<br>        print(f&quot;Executing task: {self.name}&quot;)<br>        # Simulating some task execution<br>        time.sleep(3)</pre><p>You want to extend the functionality of the app by having the tasks timed. You could achieve that as follows:</p><pre>...<br><br># Define a convenient API for the Task class<br>        <br>class TimerContext:<br>    def __enter__(self):<br>        self.start_time = time.time()<br>        print(&quot;Timer started&quot;)<br>        return self<br><br>    def __exit__(self, exc_type, exc_value, traceback):<br>        self.end_time = time.time()<br>        elapsed_time = self.end_time - self.start_time<br>        print(f&quot;Timer stopped. Elapsed time: {elapsed_time} seconds&quot;)<br><br><br>class TimedTask(TaskADT):<br>    def __init__(self, task_instance: TaskADT):<br>        self.task = task_instance<br><br>    def execute(self):<br>        # run the execute method iside the timer context you created above.<br>        with TimerContext():<br>            self.task.execute()</pre><p>That way, you can create an instance of the Task class, wrap it in a TimedTask instance, and then execute the task using the execute method of the TimedTask class which abstracts away the timing logic.</p><pre>task_instance = Task(&quot;Sample Task&quot;)<br>timed_task = TimedTask(task_instance)<br>timed_task.execute()</pre><h4>Reset a change.</h4><p>Imagine an application with global configurations. You want to run the application with some of the configurations changed to see how it would behave in such cases. But you want the application to return to the original state immediately after your run completes.</p><p>You can do that using context managers as shown below:</p><pre>from contextlib import contextmanager<br><br># Global configuration dictionary<br>global_config = {&#39;debug_mode&#39;: False, &#39;timeout&#39;: 10}<br><br>@contextmanager<br>def temporary_config_change(new_value, key):<br>    # Save the original value<br>    original_value = global_config[key]<br>    # Change the global configuration value temporarily<br>    global_config[key] = new_value<br><br>    yield # allow execution to return to context<br><br>    #reset config.<br>    global_config[key] = original_value<br><br><br># Example usage<br>print(&quot;Original Configuration:&quot;, global_config)<br>with temporary_config_change(True, &#39;debug_mode&#39;):<br>    print(&quot;Configuration Inside Context:&quot;, global_config)<br>    # Some code that runs with the modified configuration<br><br><br>print(&quot;Configuration After Context:&quot;, global_config)<br><br># Original Configuration: {&#39;debug_mode&#39;: False, &#39;timeout&#39;: 10}<br># Configuration Inside Context: {&#39;debug_mode&#39;: True, &#39;timeout&#39;: 10}<br># Configuration After Context: {&#39;debug_mode&#39;: False, &#39;timeout&#39;: 10}</pre><p>I have used a function-based context manager in this case.</p><h4>Start-stop.</h4><p>Imagine an application that simulates wind speeds and direction. You want to start the simulation and use the data points generated. You then want to stop the simulation automatically after you are done with the data points.</p><p>This can be achieved using context managers as shown below:</p><pre>import time<br>import random<br><br>class WindSimulation:<br>    def __enter__(self):<br>        # Simulate starting the wind simulation<br>        print(&quot;Wind simulation started&quot;)<br>        return self<br><br>    def __exit__(self, exc_type, exc_value, traceback):<br>        # Simulate stopping the wind simulation<br>        print(&quot;Wind simulation stopped&quot;)<br><br>    def generate_wind_data(self):<br>        # Simulate generating random wind direction and speed<br>        direction = random.randint(0, 360)  # Wind direction in degrees<br>        speed = random.uniform(0, 30)       # Wind speed in meters per second<br>        return direction, speed<br><br>class Plane:<br>    def __init__(self, name):<br>        self.name = name<br><br>    def fly_in_wind(self, wind_direction, wind_speed):<br>        # Simulate the plane adjusting its course based on wind<br>        print(f&quot;{self.name} flying in wind - Direction: {wind_direction}, Speed: {wind_speed} m/s&quot;)<br><br># Example usage<br>with WindSimulation() as wind_sim:<br>    # Inside this block, you can get simulated wind data<br>    for i in range(5):<br>        wind_direction, wind_speed = wind_sim.generate_wind_data()<br><br>        # Create a plane and simulate it flying in the current wind conditions<br>        plane = Plane(f&quot;Plane {i+1}&quot;)<br>        plane.fly_in_wind(wind_direction, wind_speed)<br><br>        time.sleep(1)  # Simulating some time between wind updates<br><br># Outside the &#39;with&#39; block, the wind simulation is stopped automatically<br>print(&quot;Wind simulation context exited&quot;)</pre><p>This code uses a WindSimulation context manager to simulate changing wind conditions. Inside the context, it generates random wind data and simulates planes adjusting to the wind. After the loop, the context is exited and &quot;Wind simulation context exited&quot; is printed.</p><h3>Conclusion.</h3><p>The Python with statement is a powerful tool to have in your arsenal as it is most commonly used for IO resource management (files, directories, network, etc). I hope this article opens your eyes to the possibilities that can be afforded to you if you are a little creative with how you use context managers.</p><p>Next time you are writing a piece of software, consider where context managers might be of use to you.</p><p>Cheers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9edf368a3be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vectorization: Replace your slow Python loops with this technique.]]></title>
            <link>https://medium.com/@orichcaspertheghost/vectorization-replace-your-slow-python-loops-with-this-technique-922ef2133ed7?source=rss-4c803599bd94------2</link>
            <guid isPermaLink="false">https://medium.com/p/922ef2133ed7</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[casper orich]]></dc:creator>
            <pubDate>Fri, 19 Jan 2024 12:07:22 GMT</pubDate>
            <atom:updated>2024-01-19T12:07:22.966Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2kAExfjofH7w8HBL" /><figcaption>Photo by <a href="https://unsplash.com/@tine999?utm_source=medium&amp;utm_medium=referral">Tine Ivanič</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Python is an excellent general-purpose programming language. Part of that is due to its dynamic typing, meaning the variable type is not determined until execution time. This allows Pythonistas not to have to declare types explicitly, hence the extremely simple and readable code characteristic of Python.</p><p>This simplicity, however, comes with some drawbacks. Determining the type of a variable before execution is beneficial as you can then do some optimization memory and performance-wise.</p><p>This area of optimization can be leveraged to make your code more efficient; you will learn how this can be achieved using vectorization.</p><p><strong>A loopy code.</strong></p><p>Consider the following piece of code.</p><pre>DATA = [random() for _ in range(50_000_000)]<br>mean = sum(DATA) / len(DATA)<br>result = [DATA[i] - mean for i in range(len(DATA))]</pre><p>It is doing a normalization operation on items DATA by subtracting the mean. A Python loop is used in this case, going through every item in the DATA list. The thing with Python lists is, as mentioned earlier, the runtime does not know the type of the individual items in it. We know for sure it is a list of integers, but the runtime doesn&#39;t. To the runtime, it is a list of object pointers, so it has to look at where it points, get the data stored, determine its type, and then use its subtraction function, and finally store the result in another object.</p><p>The thing is, CPUs are very fast and efficient, especially for numerical operations involving primitive types (integers, floats, etc). Python objects are, however, complex types that a CPU would struggle with a little bit, and indeed, you can confirm this by running the code inside a timing context to see how long it will take to execute.</p><p>Create a new file in the same directory and call it benchmark.py then insert the following code.</p><pre>import timeit<br>from contextlib import contextmanager<br><br>@contextmanager<br>def timing_context():<br>    start_time = timeit.default_timer()<br>    yield<br>    end_time = timeit.default_timer()<br>    elapsed_time = end_time - start_time<br>    print(f&quot;Elapsed time: {elapsed_time} seconds&quot;)</pre><p>This context we are creating will help us time our code. The specifics of the code are beyond the scope of this article.</p><p>Move your code into the context, and you can now time it.</p><pre>from benchmark import timing_context<br>from random import random<br><br>DATA = [random() for _ in range(50_000_000)]<br><br>with timing_context():<br>    mean = sum(DATA) / len(DATA)<br>    result = [DATA[i] - mean for i in range(len(DATA))]</pre><p>The output for me is Elapsed time: 5.475195631001043 seconds,5 seconds might seem like a short time until you realize that the <a href="https://www.supportivecareaba.com/statistics/average-attention-span#:~:text=The%20average%20attention%20span%20of,goldfish&#39;s%209%20second%20attention%20span!">average attention span for a human</a> is 8 seconds, so you are very close to losing your user.</p><p><strong>Vectorization</strong></p><p>One way to fix this problem is by using a statically typed language, like C++, but your entire codebase is in Python, and you swear by it. Luckily, some engineers who are a little more clever than you already figured this out; they wrote a library using C and called it Numpy. Now, simply by using this library, you can realize significant performance gains for your applications.</p><p>That said, let us define vectorization in this sense.</p><p>Vectorization is the process of converting operations into vectorized form, a form in which they can be performed on entire arrays or sequences of data once rather than iterating over each element one by one.</p><p>So, the same code can be vectorized as follows. I have already included the timing context.</p><pre>from benchmark import timing_context<br>import numpy as np<br><br>DATA = np.random.rand(50_000_000)<br><br>with timing_context():<br>    mean = DATA.sum() / len(DATA)<br>    result = DATA - mean</pre><p>DATA is converted into a Numpy array, which will be represented internally as a C array, a simpler, lower-level implementation. The sum and normalization can be performed on the entire array once.</p><p>Running the code gives Elapsed time: 0.1338844349993451 seconds , That was lightning fast. A sub-second operation now.</p><p><strong>Some practical examples</strong></p><p>Consider a delivery warehouse. Employees are tasked with packing into 4 sizes of boxes: small, medium, large, and extra large (S, M, L, XL). They are paid according to the number of boxes packed daily, with the larger boxes paying more. The number of boxes packed is stored in a Python list, the first item in the list being boxes of small size packed, the second being medium-sized, and so on till extra large.</p><pre>import numpy as np<br><br># employee = [S,M,L,XL]<br><br>harry = [89, 70, 66, 40]<br>mary = [50, 67, 78, 81]<br>danny = [56, 45, 90, 92]<br>tracey = [56, 24, 9, 23]<br><br>#pay per box size<br>pay = {&quot;S&quot;:20,&quot;M&quot;:40,&quot;L&quot;:80,&quot;XL&quot;:160}</pre><p><strong>#1.Element-wise operations, e.g., addition, subtraction, multiplication, division</strong></p><p>How many S, M, L, and XL boxes were packed that day?</p><p>The first step would be to convert the lists into Numpy arrays. Then, use the efficient element-wise addition by Numpy.</p><pre><br>...<br><br>#convert to numpy arrays<br>harry = np.array(harry)<br>mary = np.array(mary)<br>danny = np.array(danny)<br>tracey = np.array(tracey)<br><br>total_boxes = harry + mary + danny + tracey<br>print(total_boxes)<br><br># [251 206 243 236]</pre><p>Take a moment to consider how this would be implemented using loops to appreciate the simplicity afforded by vectorization.</p><p><strong>#2. Aggregation functions like np.sum(), np.mean(), np.max(), np.min(), etc</strong></p><p>What is the total number of boxes packed by Tracey? You can use the np.sum() function to perform this.</p><pre><br>...<br><br>total = np.sum(tracey)<br>print(total)<br><br># 112</pre><p>Who packed the highest number of XL boxes? For this case, you could optimize the data structure by converting it into a 2D array and then use np.argmax() to get the index of the highest value.</p><pre>...<br>#create a 2D array<br>arrays = np.array([harry,mary,danny,tracey])<br># Extract elements at index 3 (the XL boxes) from each row<br>xl_boxes = arrays[:, 3]<br>index_of_highest_value = np.argmax(xl_boxes)<br>print(index_of_highest_value)<br>#2 - corresponding to danny</pre><p><strong>#3. Logical operations.</strong></p><p>Settle the dispute: did Mary pack more S, M, L, and XL boxes than Danny, or is she being delusional?</p><p>A simple logical operation on the arrays could give some insight.</p><pre>...<br><br>mask = (mary &gt; danny)<br>print(mask)<br><br>#[False  True False False]</pre><p>Nope, she did pack more medium-sized boxes than Danny, but the rest she didn&#39;t.</p><p><strong>#4. Custom Universal functions</strong>.</p><p>Calculate the total amount owed to Tracey for her day’s work.</p><p>numpy does provide some useful universal functions, but they will not help us calculate the total, so what do you do? You create your own.</p><pre><br>...<br><br>def calculate_total(item,pay):<br>    return item * pay<br><br>#create a custom ufunction from calculate total<br>custom_ufunc = np.frompyfunc(calculate_total, 2, 1)<br>#apply the ufunc to the tracey array<br>pay_per_size = custom_ufunc(<br>        tracey,<br>        np.array( list(pay.values()) ) <br>    )<br>print(pay_per_size)<br>#[1120 960 720 3680]<br><br>total = np.sum(pay_per_size)<br>print(total)<br>#6480</pre><p>In the above snippet, you create a Python function calculate_total, which takes the item and pay as parameters and returns their product. You then create a NumPy ufunc custom_ufunc using np.frompyfunc based on calculate_total. You then apply the ufunc to the tracey array and the array of pay values obtained from pay.values(). This results in an array pay_per_size where each element is the product of the corresponding elements in tracey and the pay values. Finally, you calculate the total sum of the elements in, resulting in the final total value.</p><p>Those are just a few examples of applications. Use your imagination to come up with solutions for your use case.</p><p><strong>Limitations</strong></p><p>Knowing the power of vectorization, you might be tempted to apply it to every loop you use in your code. You will quickly realize that some problems are better solved with just regular loops. Consider the following limitations :</p><ol><li><strong>Extremely high memory usage.</strong></li></ol><p>Performing operations on very large NumPy arrays can lead to high memory usage, and in extreme cases, it may result in running out of memory. Let’s consider an example where creating and manipulating large arrays can consume a significant amount of memory:</p><pre>import numpy as np<br><br># Create a very large array<br>large_array = np.ones((10**6, 10**6), dtype=np.float64)<br><br># Perform an operation that duplicates the array in memory<br>result_array = large_array + large_array<br><br># Note: The above operation is not an in-place operation; it creates a new array in memory.</pre><p>In this example, a large 2D array with dimensions 10^6 x 10^6 is created using np.ones. The subsequent operation large_array + large_array creates a new array in memory where each element is the sum of the corresponding elements from large_array. This results in a temporary array that requires as much memory as the original array, effectively doubling the memory usage during the operation.</p><p>In practice, you must be cautious when dealing with large arrays, especially if your machine’s memory capacity is limited. It’s important to consider whether your operation is memory-efficient and whether it can be done in place to minimize memory usage. Additionally, using more memory-efficient data types (float32 instead of float64, for example) can also help reduce memory consumption for larger arrays.</p><p><strong>2. Only supported operations are fast</strong></p><p>There are scenarios where the performance bottleneck is inherent, and particular operations simply cannot be vectorized due to their nature. One typical example is string manipulation, which often involves character-wise operations and can be inherently challenging to vectorize efficiently. Consider an example:</p><pre>import numpy as np<br>import time<br><br># Generate a large array of random strings<br>large_array_strings = np.array([&#39;abc&#39;, &#39;def&#39;, &#39;ghi&#39;] * (10**5))<br><br># Slow Python loop to perform character-wise manipulation<br>def slow_string_manipulation_loop(array):<br>    result = np.empty_like(array, dtype=object)<br>    for i in range(len(array)):<br>        result[i] = array[i].upper()<br>    return result<br><br># Vectorized operation using NumPy&#39;s vectorize function<br>vectorized_string_manipulation = np.vectorize(lambda x: x.upper())<br><br># Measure time for the slow loop<br>start_time = time.time()<br>result_slow_loop = slow_string_manipulation_loop(large_array_strings)<br>slow_loop_time = time.time() - start_time<br><br># Measure time for the vectorized operation<br>start_time = time.time()<br>result_vectorized = vectorized_string_manipulation(large_array_strings)<br>vectorized_time = time.time() - start_time<br><br># Compare times<br>print(f&quot;Time taken by slow loop: {slow_loop_time} seconds&quot;)<br>print(f&quot;Time taken by vectorized operation: {vectorized_time} seconds&quot;)</pre><p>In this example, you have an array of strings and want to perform a character-wise manipulation: converting all characters to uppercase. The slow_string_manipulation_loop function uses a Python loop to iterate through each string and perform the operation, while the vectorized_string_manipulation uses NumPy&#39;s vectorize function to apply the operation element-wise.</p><p>String operations inherently involve character-wise manipulations, and in some cases, vectorization may not provide significant speedup due to the nature of the operation. In such scenarios, the bottleneck may be unavoidable, and optimizing the loop becomes crucial for improving performance.</p><p><strong>3. Performance gains are only significant for bulk operation</strong>s.</p><p>If your data is in the tens or hundreds of elements, maybe write a loop. The performance gains will be insignificant compared to the added complexity you introduce by vectorization.</p><p><strong>Conclusion</strong></p><p>Vectorization is an essential technique to realize performance gains in your code. This article is to open your eyes to the possibilities. Use your imagination to take full advantage of the technique.</p><p>Happy coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=922ef2133ed7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What if we didn't have Python classes?]]></title>
            <link>https://medium.com/@orichcaspertheghost/what-if-we-didnt-have-python-classes-d60005a13e51?source=rss-4c803599bd94------2</link>
            <guid isPermaLink="false">https://medium.com/p/d60005a13e51</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[oop]]></category>
            <dc:creator><![CDATA[casper orich]]></dc:creator>
            <pubDate>Mon, 15 Jan 2024 08:55:23 GMT</pubDate>
            <atom:updated>2024-01-15T08:55:23.509Z</atom:updated>
            <content:encoded><![CDATA[<h3>What if we didn&#39;t have Python classes? I tried to replace classes with functions; here is what I learned.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MwV8IuVmdatmYLNZ" /><figcaption>Photo by <a href="https://unsplash.com/@cdr6934?utm_source=medium&amp;utm_medium=referral">Chris Ried</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Object Oriented Programming (OOP) is an essential tool for the modern-day programmer. And you won&#39;t have to look far to get examples of software built using this paradigm. However, there is a tendency to overuse objects, leading to convoluted code that compromises readability, maintainability, and even data integrity.</p><p>Consider a scenario where a class might be used to represent a simple configuration:</p><pre>class Configuration:<br>    def __init__(self):<br>        self.config_data = {}<br><br>    def set_config(self, key, value):<br>        self.config_data[key] = value<br><br>    def get_config(self, key):<br>        return self.config_data.get(key)<br><br># Example usage<br>config_instance = Configuration()<br>config_instance.set_config(&#39;username&#39;, &#39;user123&#39;)<br>config_instance.set_config(&#39;password&#39;, &#39;pass456&#39;)<br><br>username = config_instance.get_config(&#39;username&#39;)<br>password = config_instance.get_config(&#39;password&#39;)<br><br>print(&quot;Username:&quot;, username)<br>print(&quot;Password:&quot;, password)</pre><p>The configuration class is used to store key-value pairs representing configuration settings. However, using a class might be considered over-engineering for key-value storage.</p><p><strong>Using functions</strong></p><pre>config_data = {}<br><br>def set_config(key, value):<br>    config_data[key] = value<br><br>def get_config(key):<br>    return config_data.get(key)<br><br># Example usage<br>set_config(&#39;username&#39;, &#39;user123&#39;)<br>set_config(&#39;password&#39;, &#39;pass456&#39;)<br><br>username = get_config(&#39;username&#39;)<br>password = get_config(&#39;password&#39;)<br><br>print(&quot;Username:&quot;, username)<br>print(&quot;Password:&quot;, password)</pre><p>In this alternative example, functions (set_config and get_config) are used with a global dictionary to store configuration settings. This avoids the need for a class and provides a more straightforward and readable way to handle simple configurations.</p><p>Choosing functions over classes in this context simplifies the code and reduces the unnecessary overhead of creating instances, especially when the problem can be adequately addressed with a more straightforward approach.</p><p>This is not to say that classes are evil; classes and OOP generally have their place. In an <a href="http://userpage.fu-berlin.de/~ram/pub/pub_jf47ht81Ht/doc_kay_oop_en">email exchange</a>, Alan Kay, the man who coined the term OOP and brought it to the masses, spooked by the misunderstanding and misuse of the concept, clarified what he meant by object-oriented:</p><p><em>“OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things.”<br>~ Alan Kay</em></p><p>What do you learn from here? You should consider applying OOP if and only when you want to achieve the following:</p><ul><li>message passing</li><li>Encapsulation</li><li>Dynamic binding</li></ul><p>More often than not, functions are sufficient to structure your code. Always consider functions first until the scenarios mentioned above pop up.</p><p>With that said, I went into a bit of a rabbit hole, scouring through my codebases and looking for where I might have run afoul of these guidelines. Needless to say, there were many such occurrences. Then I started wondering, What if I replaced all classes with functions? What if Python classes were never included in the language? Would it still be possible to achieve the functionality of classes without them? Then I stopped wondering, and this is what I found out.</p><p>Consider this code: The Account class models a simple bank account with withdrawal and deposit functionalities.</p><pre>class Account:<br>    def __init__(self,account_name, account_number, initial_balance=0):<br>        self.account_name = account_name<br>        self.account_number = account_number<br>        self.balance = initial_balance<br>        self.transactions = []<br><br>    def deposit(self, amount):<br>        if amount &gt; 0:<br>            self.balance += amount<br>            self.transactions.append(amount)<br>            return True<br>        else:<br>            print(&quot;Invalid deposit amount. Please enter a positive value.&quot;)<br>            return False<br><br>    def withdraw(self, amount):<br>        if amount &gt; 0 and amount &lt;= self.balance:<br>            self.balance -= amount<br>            self.transactions.append(-abs(amount))<br>            return True<br>        else:<br>            print(&quot;Invalid withdrawal amount. Please enter a valid amount.&quot;)<br>            return False<br><br>    def get_transactions(self):<br>        return self.transactions<br><br>    def get_balance(self):<br>        return self.balance<br><br>    def get_account_detail(self):<br>        return f&quot;Acc. name: {self.account_name}\n Acc. No.: {self.account_number}&quot;</pre><p>You could do a lot to improve this code, but I wanted it not to have any classes, just functions. How would I go about it? Enter …</p><p><strong>Closures</strong></p><p>A closure in Python is a nested function with access to variables in its lexical scope, even if the scope has finished execution. Essentially, closure allows a function to retain the context in which it was created.</p><pre><br>def outer(message):<br>    a = &quot;Hello world, &quot;<br>    def inner():        <br>        print(a + message)<br>    return inner<br><br><br>fnc = outer(&#39;I am a ghost&#39;)<br>fnc()</pre><p>When outer is called, it returns the inner function, creating a closure where message is remembered as &quot; am a ghost” .The closure (fnc) can then be used to call the inner function and will correctly use the remembered value of message</p><p>You can see how this can be useful. The class can be rewritten as follows using closures.</p><pre>def account(*,account_name, account_number, initial_balance=0):<br>    account_name = account_name<br>    account_number = account_number<br>    balance = initial_balance<br>    transactions = []<br><br>    <br>    def deposit(amount):        <br>        nonlocal balance<br>        if amount &gt; 0:            <br>            balance += amount<br>            transactions.append(amount)<br>            return True<br>        else:<br>            print(&quot;Invalid deposit amount. Please enter a positive value.&quot;)<br>            return False<br><br>    def withdraw(amount):<br>        nonlocal balance<br>        if amount &gt; 0 and amount &lt;= balance:<br>            balance -= amount<br>            transactions.append(-abs(amount))<br>            return True<br>        else:<br>            print(&quot;Invalid withdrawal amount. Please enter a valid amount.&quot;)<br>            return False<br><br>    def get_transactions():<br>        return transactions<br><br>    def get_balance():<br>        return balance<br><br>    def get_account_detail():<br>        return f&quot;Acc. name: {account_name}\n Acc. No.: {account_number}&quot;<br><br><br>    return {<br>        &#39;deposit&#39;:deposit,<br>        &#39;withdraw&#39;:withdraw,<br>        &#39;get_transactions&#39;:get_transactions,<br>        &#39;get_balance&#39;:get_balance,<br>        &#39;get_account_detail&#39;:get_account_detail<br>    }<br></pre><p>The Account class has been replaced by account() function, which ‘encloses’ the functions deposit(), withdraw(), get_transactions(), get_balance() and get acount_details(). To ensure you can access all the functions, account returns a dictionary with the keys being the name of the function and the value being the function itself.</p><p>The account function acts as the constructor, creating scope for the closure. Now, all you need to do to call an inner function is to get it from the returned dictionary and pass in its arguments, as shown below:</p><pre>my_account = account(account_name=&quot;John Doe&quot;, account_number=&quot;123456&quot;, initial_balance=1000)<br># Deposit and Withdrawal<br>my_account[&#39;deposit&#39;](500)<br>my_account[&#39;withdraw&#39;](200)<br><br># Get Transactions and Balance<br>print(&quot;Account Detail:\n&quot;, my_account[&#39;get_account_detail&#39;]())<br>print(&quot;Transactions:&quot;, my_account[&#39;get_transactions&#39;]())<br>print(&quot;Current Balance:&quot;, my_account[&#39;get_balance&#39;]())</pre><p><strong>Dot notation</strong></p><p>It is a little cumbersome to use the dictionary[‘key’] notation, especially in this scenario where you are coming from a class. Keeping the dot notation for consistency’s sake would be much better.</p><p>This is where you cheat a little bit. You could create a class with the attributes you need or return a modified dictionary that can allow for dot notations, but all that would involve classes.</p><p>Instead, you could opt for SimpleNamespace class, which is a simple container for creating objects with attributes. Granted, it is still a class, but at least you won&#39;t have written the word class in your code :).</p><pre>from types import SimpleNamespace<br><br>def account(*,account_name, account_number, initial_balance=0):<br>    account_name = account_name<br>    account_number = account_number<br>    balance = initial_balance<br>    transactions = []<br><br>    def deposit(amount):        <br>        nonlocal balance<br>        if amount &gt; 0:<br>            print(balance)<br>            balance += amount<br>            transactions.append(amount)<br>            return True<br>        else:<br>            print(&quot;Invalid deposit amount. Please enter a positive value.&quot;)<br>            return False<br><br>    def withdraw(amount):<br>        nonlocal balance<br>        if amount &gt; 0 and amount &lt;= balance:<br>            balance -= amount<br>            transactions.append(-abs(amount))<br>            return True<br>        else:<br>            print(&quot;Invalid withdrawal amount. Please enter a valid amount.&quot;)<br>            return False<br><br>    def get_transactions():<br>        return transactions<br><br>    def get_balance():<br>        return balance<br><br>    def get_account_detail():<br>        return f&quot;Acc. name: {account_name}\n Acc. No.: {account_number}&quot;<br><br><br>    return SimpleNamespace(<br>        deposit=deposit,<br>        withdraw=withdraw,<br>        get_transactions=get_transactions,<br>        get_balance=get_balance,<br>        get_account_detail=get_account_detail<br>    )</pre><p>Now, instead of returning a dictionary, return a SimpleNamespace object which will allow you to have your dot notation. Now you can do this.</p><pre>my_account = account(account_name=&quot;John Doe&quot;, account_number=&quot;123456&quot;, initial_balance=1000)<br># Deposit and Withdrawal<br>my_account.deposit(500)<br>my_account.withdraw(200)<br><br><br># Get Transactions and Balance<br>print(&quot;Account Detail:\n&quot;, my_account.get_account_detail())<br>print(&quot;Transactions:&quot;, my_account.get_transactions())<br>print(&quot;Current Balance:&quot;, my_account.get_balance())</pre><p>Much better.</p><p><strong>Inheritance</strong></p><p>I am not a big fan of inheritance. Granted, it has its place, but again, more often than not, it is abused. As mentioned earlier, message passing, encapsulation, and dynamic binding should be why you use OOP. Notice the lack of inheritance in what is essential. Consider <a href="https://medium.com/swlh/the-best-way-to-understand-composition-in-python-5-case-studies-and-solution-4b23a6a2cc38">composing</a> your code instead.</p><p>That said, how would inheritance be achieved without classes? Consider another account, call it a savings goal account, where withdrawals can only happen after a set amount has been reached.</p><pre>class SavingsGoalAccount(Account):<br>    def __init__(self, account_name, account_number, goal_amount):<br>        super().__init__(account_name, account_number)<br>        self.goal_amount = goal_amount<br><br>    def withdraw(self, amount):<br>        if self.balance  &gt;= self.goal_amount:<br>            self.balance -= amount<br>            self.transactions.append(-abs(amount))<br>            return True<br>        else:<br>            print(&quot;Invalid withdrawal amount or goal not reached.&quot;)<br>            return False</pre><p>the SavingsGoalAccount is a subclass of the original Account class, defining its own withdraw function that handles the goal amount check. The class can be used as follows :</p><pre>savings_account = SavingsGoalAccount(account_name=&quot;Savings&quot;, account_number=&quot;789012&quot;, goal_amount=5000)<br><br># Deposit and Withdrawal (only allowed when the goal is reached)<br>savings_account.deposit(2000)<br>savings_account.deposit(3000)<br>print(savings_account.get_balance())<br>savings_account.withdraw(1000)  # This withdrawal is allowed<br>savings_account.withdraw(2000)  # This withdrawal is not allowed<br><br>print(&quot;Transactions:&quot;, savings_account.get_transactions())<br>#Transactions: [2000, 3000, -1000]</pre><p>Using the concept of closures, you could write the same child class as follows:</p><pre>def savings_goal_acount(*,account_name, account_number, goal_amount):<br>    parent = account #referring to the account function<br>    child = parent(account_name=account_name,account_number=account_number)   <br>    goal_amount = goal_amount<br><br>    def withdraw(amount):        <br>        if child.get_balance() &gt;= goal_amount:            <br>            child.set_balance(child.get_balance() - amount )            <br>            child.transactions.append(-abs(amount))            <br>            return True<br>        else:<br>            print(&quot;Invalid withdrawal amount or goal not reached.&quot;)<br>            return False<br><br>    child.withdraw = withdraw<br>    return child</pre><p>Inside the savings_goal_account function, you define account as your parent, then create the child from the parent using the parameters passed into savings_goal_account. You then proceed to define the withdraw function for the child, and with child.withdraw = withdraw, you manually override the parent&#39;s withdraw function. Finally, return the child.</p><p>With that done, you simply substitute the SavingsGoalAccount class with the savings_goal_account function, and you have your inheritance:</p><pre>savings_account = savings_goal_acount(account_name=&quot;Savings&quot;, account_number=&quot;789012&quot;, goal_amount=5000)<br><br># Deposit and Withdrawal (only allowed when the goal is reached)<br>savings_account.deposit(2000)<br>savings_account.deposit(3000)<br>print(savings_account.get_balance())<br>savings_account.withdraw(1000)  # This withdrawal is allowed<br>savings_account.withdraw(2000)  # This withdrawal is not allowed<br><br>print(&quot;Transactions:&quot;, savings_account.get_transactions())<br>#Transactions: [2000, 3000, -1000]</pre><p><strong>Conclusion</strong></p><p>With closures, you have a powerful tool that can help eliminate unnecessary use of classes. Not to say you should write all your classes like this, but to open your eyes to the possibilities.</p><p>Happy coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d60005a13e51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop using lists for everything. Try this instead.]]></title>
            <link>https://medium.com/@orichcaspertheghost/stop-using-lists-for-everything-try-this-instead-d2da29929220?source=rss-4c803599bd94------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2da29929220</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-web-developer]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[casper orich]]></dc:creator>
            <pubDate>Tue, 05 Dec 2023 09:45:21 GMT</pubDate>
            <atom:updated>2024-01-26T09:17:54.367Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yEVZN00YfQqgF9Xp" /><figcaption>Photo by <a href="https://unsplash.com/@qwitka?utm_source=medium&amp;utm_medium=referral">Maksym Kaharlytskyi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Lists are a great data structure in Python, they help us store and manipulate collections of items. They are mutable, meaning we can add, remove, and modify the elements. The power of lists cannot be overstated, which explains their ubiquity in Python codebases.</p><p>You should, however, not let the ubiquity blind you from alternative data structures that may have better performance for certain use cases. In this article, you will learn of one such structure, explore its strengths and weaknesses, and discover how it can improve the performance of your code.</p><p><strong>Enter sets</strong></p><p>Say you want to create a unique collection of items from two lists ( removing the duplicates), an intuitive solution would be to loop through the elements of both lists, checking that the element does not already exist in the resultant list.</p><pre>def unique_list(list1,list2):<br>    result = []<br>    for item in list1 + list2:<br>        if item not in result:<br>            result.append(item)<br>    return result<br><br><br>list1 = [1,2,3,4]<br>list2 = [3,4,5,6]<br><br>print(unique_list(list1,list2))<br>#[1, 2, 3, 4, 5, 6]</pre><p>All seems well, the code works and you get your desired result. Upon close inspection, however, you will notice a glaring inefficiency. Every time item not in result is run, the Python runtime has to go through all items in result, checking that said item is not among its elements.</p><p>One way we can improve this code is to use <a href="https://realpython.com/python-sets/">sets</a>. A set is an unordered collection of unique elements, the elements are of immutable type but the set itself is mutable. It is this set of characteristics that makes sets a simple but powerful data structure.</p><p>That same result can be achieved with sets as follows:</p><pre>def unique_list(list1,list2):<br>    result = set() # initialize an empty set<br>    for item in list1 + list2:<br>        if item not in result:<br>            result.add(item)# add item to set<br>    return list(result)<br><br>list1 = [1,2,3,4]<br>list2 = [3,4,5,6]<br><br>print(unique_list(list1,list2))<br>#[1, 2, 3, 4, 5, 6]</pre><p>By changing only the data structure used, you can achieve much better-optimized solutions. You can confirm this by testing the two approaches with a larger input.</p><pre>import timeit<br>from functools import partial<br><br>def unique_list_using_lists(list1,list2):<br>    result = []<br>    for item in list1 + list2:<br>        if item not in result:<br>            result.append(item)<br>    return result<br><br>def unique_list_using_sets(list1,list2):<br>    result = set()<br>    for item in list1 + list2:<br>        if item not in result:<br>            result.add(item)<br>    return list(result)<br><br>list1 = list(range(0,1_000))<br>list2 = list(range(500,1_000))<br><br># Create partially-applied functions<br>partial_function_lists = partial(unique_list_using_lists, list1, list2)<br>partial_function_sets = partial(unique_list_using_sets, list1,list2)<br><br># Measure the execution time of partially-applied function_lists<br>time_one = timeit.timeit(partial_function_lists, number=1000)<br><br># Measure the execution time of partially-applied function_sets<br>time_two = timeit.timeit(partial_function_sets, number=1000)<br><br>print(&quot;Time for function_lists:&quot;, time_one)<br>print(&quot;Time for function_sets:&quot;, time_two)<br><br>#Time for function_lists: 6.59087880800007<br><br>#Time for function_sets: 0.11217345100021703</pre><p>You will notice the function that uses sets performs significantly better than the one using lists. This is because sets are optimized for membership testing. A membership test on a set will run in constant time as it utilizes hash tables while on lists, it will run in O(n) where n is the length of the list.</p><p>It gets better, because, as mentioned earlier, sets are a collection of unique items. By type-casting a list into a set, you can achieve the same result with this minimal code.</p><pre>result = list(set(list1+list2))<br>print(result)</pre><p><strong>Set operations</strong></p><p>A set is bundled with a couple of useful operations you can take advantage of:</p><p><strong>Union</strong></p><p>A union of two sets is a set containing elements in either set.</p><p>Imagine you are working with a system that tracks the interests of users on an online platform. Each user has a set of interests, and you want to create a combined set of all unique interests across multiple users. This combined set can be useful for purposes such as recommending content or analyzing popular topics. Here’s an illustrative Python example:</p><pre># User interests<br>user1_interests = {&#39;python&#39;, &#39;data science&#39;, &#39;machine learning&#39;}<br>user2_interests = {&#39;machine learning&#39;, &#39;deep learning&#39;, &#39;data engineering&#39;}<br>user3_interests = {&#39;python&#39;, &#39;web development&#39;, &#39;data science&#39;}<br><br># convert to sets<br>user1_interests_set,user2_interests_set,user3_interests_set  = set(user1_interests),set(user2_interests),set(user2_interests<br><br># Combine unique interests from all users<br>all_interests = user1_interests.union(user2_interests, user3_interests)<br># or all_interests = user1_interests | user2_interests | user3_interests<br><br>print(&quot;Combined Interests:&quot;, all_interests)</pre><p><strong>Intersection</strong></p><p>An intersection of two sets is a set containing elements only in both sets.</p><p>You can use the intersection operation to find the common interests among users, identifying shared interests that could lead to connecting users with similar preferences.</p><pre># User interests<br>user1_interests = {&#39;python&#39;, &#39;data science&#39;, &#39;machine learning&#39;}<br>user2_interests = {&#39;machine learning&#39;, &#39;deep learning&#39;, &#39;data engineering&#39;}<br>user3_interests = {&#39;python&#39;, &#39;web development&#39;, &#39;data science&#39;}<br><br># Find common interests among user1 and 3<br>common_interests = user1_interests.intersection(user3_interests)<br># or common_interests = user1_interests &amp; user3_interests<br><br>print(&quot;Common Interests:&quot;, common_interests)</pre><p><strong>Difference</strong></p><p>The difference between two sets is a set containing elements in the first set but not in the second (left to right).</p><p>Imagine a calendar application. You can use the set difference operation to find the hours that are free for two users.</p><pre>hours_of_day = list(range(1, 13))<br>person1_schedule = [1, 2, 5, 9, 10]<br>person2_schedule = [1, 2, 3, 4, 5]<br><br># Convert schedules to sets<br>set_person1 = set(person1_schedule)<br>set_person2 = set(person2_schedule)<br><br># Find the hours that are free for both users<br>free_hours_both_users = set(hours_of_day) - (set_person1 | set_person2)<br># or free_hours_both_users = set(hours_of_day).difference(set_person1.union(set_person2))<br><br>print(&quot;Free hours for scheduling a meeting:&quot;, sorted(free_hours_both_users))<br>#Free hours for scheduling a meeting: [6, 7, 8, 11, 12]</pre><p><strong>Symmetric difference</strong></p><p>The symmetric difference between two sets is a set containing elements in the first and in the second but not in both.</p><p>What if both users would prefer to use the boardroom for their meetings, but wouldn&#39;t mind having the meetings elsewhere if it wasn&#39;t available? You could use `symmetric_difference` to identify when either user has a meeting while the other doesn&#39;t so that they can use the boardroom.</p><pre>hours_of_day = list(range(1, 13))<br>person1_schedule = [1, 2, 5, 9, 10]<br>person2_schedule = [1, 2, 3, 4, 5]<br><br># Convert schedules to sets<br>set_person1 = set(person1_schedule)<br>set_person2 = set(person2_schedule)<br><br># Find the hours that either user has a meeting while the other doesnt<br>free_hours_for_boardroom_meetings = set_person1 ^ set_person2<br>#or free_hours_both_users = set_person1.symmetric_difference(set_person2)<br><br>print(&quot;Free hours for using the boardroom:&quot;, sorted(free_hours_both_users))</pre><p><strong>Disjoint</strong></p><p>Two sets are disjoint if they have no elements in common. The isdisjoint() method returns True if the sets have no intersection, and False otherwise.</p><p>Let’s say you have two lists representing the employees who attended a training session on two different days. You want to check if any employees attended both days.</p><pre># Employee attendance on Day 1<br>day1_attendees = [&#39;Alice&#39;, &#39;Bob&#39;, &#39;Charlie&#39;, &#39;David&#39;]<br><br># Employee attendance on Day 2<br>day2_attendees = [&#39;David&#39;, &#39;Eva&#39;, &#39;Frank&#39;, &#39;Grace&#39;]<br><br>#convert to sets <br>day1_attendees_set,day2_attendees_set = set(day1_attendees),set(day2_attendees)<br><br># Check if the sets are disjoint<br>is_disjoint = day1_attendees_set.isdisjoint(day2_attendees_set)<br><br># Display the result<br>if is_disjoint:<br>    print(&quot;No common attendees. Sets are disjoint.&quot;)<br>else:<br>    print(&quot;There are common attendees. Sets are not disjoint.&quot;)</pre><p><strong>Weaknesses</strong></p><p>To say it is a weakness is a stretch, it is a product of how a set is implemented internally. That said, sets are unordered. This means that the order of the elements cannot be determined. Python does provide an ordered variant of sets called collections.OrderedSet</p><p>If the order of elements is important for your use case, then sure, go ahead and use lists or `OrderedList`. But if your use case cares more about adding, removing, and checking for the presence of an element, sets should be your go-to data structure.</p><p><strong>Conclusion</strong></p><p>With every solution, let your intuition guide your initial approach, then give yourself a chance to question that intuition. It might lead to better-optimized solutions.</p><p>Happy coding</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2da29929220" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>