<?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 Drowsy Dev on Medium]]></title>
        <description><![CDATA[Stories by Drowsy Dev on Medium]]></description>
        <link>https://medium.com/@vyperius117?source=rss-40709034902c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1PHoaoeq4YQdKStlwyfGzw.jpeg</url>
            <title>Stories by Drowsy Dev on Medium</title>
            <link>https://medium.com/@vyperius117?source=rss-40709034902c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 03:27:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vyperius117/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[RAG From Scratch with Local Models]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@vyperius117/rag-from-scratch-with-local-models-b597640b1477?source=rss-40709034902c------2"><img src="https://cdn-images-1.medium.com/max/2600/0*hr6lSo7_k4_ShPYr" width="5164"></a></p><p class="medium-feed-snippet">Introduction to RAG</p><p class="medium-feed-link"><a href="https://medium.com/@vyperius117/rag-from-scratch-with-local-models-b597640b1477?source=rss-40709034902c------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@vyperius117/rag-from-scratch-with-local-models-b597640b1477?source=rss-40709034902c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b597640b1477</guid>
            <category><![CDATA[retrieval-augmented]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[mistral]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Drowsy Dev]]></dc:creator>
            <pubDate>Wed, 08 May 2024 00:42:38 GMT</pubDate>
            <atom:updated>2024-05-08T00:42:38.528Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Securenv: Securely Setting ENV Variables with Constraints]]></title>
            <link>https://medium.com/@vyperius117/securenv-securely-setting-env-variables-with-constraints-1b8982f612ae?source=rss-40709034902c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b8982f612ae</guid>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Drowsy Dev]]></dc:creator>
            <pubDate>Sun, 28 Apr 2024 13:41:22 GMT</pubDate>
            <atom:updated>2024-04-28T13:41:22.330Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s0rqCEF3s_bpjAfO" /><figcaption>Photo by <a href="https://unsplash.com/@samferrara?utm_source=medium&amp;utm_medium=referral">Samuel Ferrara</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Environment variables are used nearly ubiquitously. Whether you’re deploying a single app or deploying a pod of containers, you’re bound to find some environment variables dictating how that application is configured. Often times, sensitive information such as usernames and passwords are set via these variables, which poses numerous potential security and administrative concerns, two of which are as follows: (1) How do you ensure that all the variables required are set during startup? and (2) How do you enforce the constraints on these variables such as length, number of characters, etc.</p><p>Regarding the former concern, common practice is to simply set the variable in an environment template that is copied by whoever is deploying the application. The default value is then often <em>recommended </em>to be changed, but not always required. In the common case where developers do not check for the presence of the environment variable being changed from the default, you now have a serious problem — anyone who can view your code base has a great first brute-force attempt at logging into that application using the default password.</p><p>As for the latter concern, this falls down the same slope — it can be a lot of extra work (and often times, not straightforward) to set and enforce complexity requirements for every application in your deployment. What your left with is the potential for non-compliant or simply insufficient passwords.</p><p>This is where <em>Securenv </em>comes in — an application I developed as a personal project to get familiar with creating an actual PyPi package. Instead of setting default passwords and hoping users update them to sufficient complexity, <em>Securenv </em>allows developers to define what variables to set, and with what requirements, using a simple metadata file. This app will read in the file and provide a textual user interface (TUI) to set all the variables, ensuring their complexity requirements are met. In this blog, I’ll walk through the basic function of <em>Securenv</em>.</p><h3>Architecture</h3><p>I say architecture pretty loosely here… <em>Securenv </em>is a small application, and that’s on purpose. When I set out to create this project, I had three goals in mind:</p><p>(1) Solve the initial problem outlined in the above section</p><p>(2) Plan, design, and implement the application with a small set of well-defined requirements</p><p>(3) Publish my first PyPi package</p><p>I’ll touch more on my experience with some of these goals at the end, but for now, let’s outline the code base.</p><p><em>Securenv </em>is built on top of <a href="https://textual.textualize.io/"><em>textual</em></a> — a library for building terminal user interfaces (TUI). Using textual allowed me to build the application rapidly, without needing to learn the ins-and-outs of how TUI’s work (though, that would be a fun project for another time). Instead, I was able to focus most of my efforts on scoping the functionality, thanks to the pre-built widgets and baked in <em>tcss</em> — a CSS-like language for styling your textual application.</p><p>Outside of textual, I also leveraged the <a href="https://pypi.org/project/schema/">schema</a> — a library for enforcing the structure of dictionary objects in Python. This allowed me to ensure that the metadata passed in by users was valid before the TUI was even spun up. Validation errors would be caught right away, and prompt the user to fix them before continuing.</p><h3>Installation and Usage</h3><p>Now, to the fun parts — actually using the application! To install, simply use pip. Note that securenv, at the time of running, is targeted as Linux systems running Python3.8 or higher.</p><pre>pip install securenv</pre><p>Once installed, the usage is as follows:</p><pre>usage: securenv [-h] metadata_file env_file<br><br>Simple TUI for Defining and Constraining Environment Variables<br><br>positional arguments:<br>  metadata_file  YAML Metadata file describing variables to set.<br>  env_file       Environment file to set ENV vars in.<br><br>options:<br>  -h, --help     show this help message and exit</pre><p>Let’s touch on the metadata file, which contains all the logic for the environment variable constraints. An example metadata YAML file would look like so:</p><pre>- var_group:<br>    title: OpenSearch Application Variables<br>    vars:<br>      - var:<br>          name: OPENSEARCH_USERNAME<br>          placeholder: &quot;admin&quot;<br>          sensitive: false<br>          complexity:<br>            max_length: 15<br>      - var:<br>          name: OPENSEARCH_PASSWORD<br>          sensitive: true<br>          placeholder: &quot;password&quot;<br>          complexity:<br>            max_length: 20<br>            min_length: 10<br>            numbers: 3<br>            symbols: 1<br>            uppercase: 1<br>- var_group:<br>    title: Redis Variables<br>    vars:<br>    - var:<br>        name: REDIS_USERNAME<br>        placeholder: &quot;admin&quot;<br>        sensitive: false<br>        complexity:<br>            max_length: 15<br>    - var:<br>        name: REDIS_PASSWORD<br>        sensitive: true<br>        placeholder: &quot;password&quot;<br>        complexity:<br>            max_length: 20<br>            min_length: 10</pre><p><em>Securenv </em>has the concept of ‘var groups’. Essentially, a var group represents a collection of environment variables that should be logically grouped together (typically, variables for the same application). Each group is required to have a ‘title’ key, representing what the variable group should be referred to as, and a collection of ‘var’ objects. Each var object represents an actual environment variable to set.</p><p>A var object has three required keys: (1) the name of the environment variable, (2) a placeholder for the UI to use in the input fields and (3) whether the variable is sensitive or not. Sensitive variables will be obfuscated during run-time to prevent pesky shoulder surfing.</p><p>The real meat of the var object is inside the optional ‘complexity’ block, which specifies the constraints placed on that specific variable. At the time of writing, the following fields are supported in this block:</p><ul><li><strong>min_length </strong>→ Minimum length of the variable (defaults to 25)</li><li><strong>max_length </strong>→ Maximum length of the variable (defaults to 5</li><li><strong>numbers </strong>→ Minimum number of digits required in the variable (defaults to 0)</li><li><strong>symbols </strong>→ Minimum number of symbols required in the variable (defaults to 0)</li><li><strong>upper_case </strong>→ Minimum number of uppercase characters required in the variable (defaults to 0)</li></ul><p><strong>NOTE</strong>: The symbols field currently checks the following list: “^!@#$”. This is due in part to constraints with the regex system in textual.</p><p>Once you’ve set up your metadata file, run the application:</p><pre>securenv mymetadata.yaml myenv.env</pre><p>You should be presented with the following screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kROhVV2pHiOWSqLSg7foSw.png" /><figcaption>TUI for Securenv</figcaption></figure><p>You’ll notice that you cannot proceed to the next screen of variables until the current screen meets the specified requirements. Once done, you’re env file will either be updated or created based on the variables specified in the TUI.</p><p>For more information or to see the code base, refer to the GitHub: <a href="https://github.com/TheDrowsyDev/securenv">https://github.com/TheDrowsyDev/securenv</a></p><h3>Introspective</h3><p>I wanted to set aside a section to talk about my experience creating the application. As mentioned prior, this was my first time creating a PyPi package, which proved to be an extremely informative experience. Up until this point, I had never worked with setuptools, defining a manifest, or building Python packages for distribution. I <strong><em>highly </em></strong>recommend building out a PyPi package yourself. It doesn’t have to be industry disrupting, I know mine sure is not, but the experience of building an application and pushing it the PyPi index is one I think every Python developer should go through at least once.</p><p>To add on to this, I want to touch on the scope of the project. I don’t expect this package to be used by… anyone. However, I did this for one reason — completion. Let me ask a question — how many applications have you started in your free time, then abandoned to let the code base collect dust? I’ll go first — a lot. So, for this project, I set out with the goal in mind to design, plan, and implement a small project with a handful of well-defined features. I started with a notepad and wrote down roughly 6 or 7 features that I wanted to implement, then wrote the code base in the matter of a couple hours. Most of the rest of my time was spent learning about GitHub actions and leverage textual’s awesome testing functions to write Pytests for the application. What I want to drive home here is that while building out huge applications like social media clones, game engines, compilers, etc. can be extremely educational and rewarding experiences, small applications such as this should not be overlooked. They allow you to experience the full cycle of development, dive into parts of engineering you may not have explored like automated code analysis, and write extensive tests without feeling burnt out from the effort of just writing the code. So, if you’re itching to write make a side project, start small. Build out bigger applications when you’re ready, but I’ve found a new love for building out projects in my spare time by scaling back my ambition and being reasonable with my attention.</p><p>If you’ve made it this far, thank you for reading! I’ve been out of the blog space for a few months due to some personal health issues, but being on the mend, I’m hoping to get back into writing more frequently, so stayed tuned for more blogs in the (hopefully) not so distance future. Cheers, and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b8982f612ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Llama2 Tokenizer: Working with the Tokenizer locally using Transformers]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@vyperius117/understanding-the-llama2-tokenizer-working-with-the-tokenizer-locally-using-transformers-2e0f9e69d786?source=rss-40709034902c------2"><img src="https://cdn-images-1.medium.com/max/2600/0*Si-ENiVZrQEzv8P4" width="4000"></a></p><p class="medium-feed-snippet">Photo by Josiah Farrow on Unsplash</p><p class="medium-feed-link"><a href="https://medium.com/@vyperius117/understanding-the-llama2-tokenizer-working-with-the-tokenizer-locally-using-transformers-2e0f9e69d786?source=rss-40709034902c------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@vyperius117/understanding-the-llama2-tokenizer-working-with-the-tokenizer-locally-using-transformers-2e0f9e69d786?source=rss-40709034902c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e0f9e69d786</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[llama-2]]></category>
            <dc:creator><![CDATA[Drowsy Dev]]></dc:creator>
            <pubDate>Sat, 09 Dec 2023 23:07:48 GMT</pubDate>
            <atom:updated>2024-01-11T19:54:13.515Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Python Beginner Series: A Simple CLI Calculator]]></title>
            <link>https://medium.com/@vyperius117/python-beginner-series-a-simple-cli-calculator-a73a23d799fd?source=rss-40709034902c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a73a23d799fd</guid>
            <category><![CDATA[argparse]]></category>
            <category><![CDATA[command-line-interface]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[introduction]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Drowsy Dev]]></dc:creator>
            <pubDate>Mon, 04 Dec 2023 02:39:11 GMT</pubDate>
            <atom:updated>2023-12-04T03:14:11.147Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nX4dq3MgU62uvlKt" /><figcaption>Photo by <a href="https://unsplash.com/@kvncnls?utm_source=medium&amp;utm_medium=referral">Kevin Canlas</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Hello, all! I’m Drowsy Dev, and thank you for taking the time to read through my <strong>first </strong>Medium article. I hope this will be the first of many blogs, and I’m excited to take this journey with all of you.</p><p>As you saw from the title, the goal of this series I’m doing is to take people from any background and get them up to speed on writing code in the Python programming language. Instead of spending time explaining every rule and detail of programming up front, I’m going to take a project-based approach to learning, and hopefully inspire you to practice writing your own projects (this really is the best way to learn after all). With all that introduction out of the way, let’s dive into a little background and set-up.</p><h3>Wait… I Thought Python was a Snake…</h3><p>Python is a high-level, interpreted programming language… is what you’ll hear most people describe the language as. While this is a technically sound explanation, I want to really break down the language, it’s purpose, and why’d you want to use it (or not).</p><p>Computers talk in binary, obviously, we do not. So, we invented programming languages to interact with computers in a more intuitive way. Python is a ‘high-level’ language because it provides a hefty abstraction between the user and the computer — you don’t need to write assembly instructions or even manually manage memory. This is all done in the background for you. The other component of that above explanation was ‘interpreted’. Programming languages can essentially be broken down into two camps — compiled and interpreted. Compiled languages are languages like Java, C, and Rust. Once you’ve written the code, you use a piece of software called a ‘compiler’ to create an executable from the source code you’ve written. Languages like Python are not compiled into binaries. Instead, you pass your source code to a special program called the ‘interpreter’ that essentially executes the code line-by-line during runtime. The differences between these two deserve their own article, so I’ll leave the explanation at that.</p><p>Now, you may be asking ‘That’s cool and all, but what can I actually <em>do </em>with Python’? The main use cases for Python are as follows:</p><ul><li>Scripting (automating one-off tasks like renaming files or uploading a file to the cloud)</li><li>Data Science (statistics + programming = AI!)</li><li>Rapid Prototyping (you got two days to get me an application… GO!)</li></ul><p>Now, because Python is a general-purpose programming language with a rich package ecosystem, you can develop anything in Python, but that doesn’t mean it’s the best fit for every job. However, it is one of if not the easiest language programming languages to pick up for those with little to no programming background. This is due in large part to its simple syntax and the abundance of online information.</p><p>Now, you might not want to use Python if you’re writing embedded systems, applications that need extremely low latency and response time, or large enterprise applications. However, don’t let that discourage you from learning the language. It’s a great place to learn the basics of Python and the demand for it commercially cannot be understated. Even if you end up working with another language in your future programming jobs, you’ll find the foundation you learn from Python can be transferred anywhere.</p><p>Okay, now that I’ve put you to sleep with the background, let’s dive into the fun stuff — set-up and actual code!</p><h3>Getting your Toolbox Together</h3><p>Before you get started, you’ll need two things:</p><ul><li>Python… (I know, shocker)</li><li>A place to write the code</li></ul><p>As far as the place to write code goes, this is more formally referred to as either a text-editor or an integrated development environment (IDE). Now, this is another topic that could have it’s own article, but I’ll give you the high-level here — a text-editor is something like notepad on Windows — you simply open it and type whatever you want, no fancy bells and whistles. Common text editors include Visual Studio Code, VIM, NeoVim, and Sublime. IDEs are like text-editors, but with a kitchen sink of tools included for building, debugging, and running your code. While IDEs are great, they also typically come with a hefty price tag and can have a larger learning curve. For this reason, I’m going to recommend installing <a href="https://code.visualstudio.com/download">VSCode</a> as your primary text-editor. It’s by far the most popular option out there, while still being very beginner friendly. As far as Python goes, just download it from the <a href="https://www.python.org/">official Python webpage</a>.</p><p>As a side note, I highly recommend installing the Python extension for VSCode. The extension provides a ton of nice language specific features like pretty syntax highlighting for your code and the ability to auto-complete code as you type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SnpdRysOJ5BNbYRNsjcQWA.png" /><figcaption>Python extension for VSCode</figcaption></figure><h3>Coding!</h3><p>Hopefully by now you have VSCode and Python installed, and your eager to go write some code. Great, let’s get started by creating a new file. Name this file main.py (.py is the extension for a Python file).</p><h4>Commenting</h4><p>The first thing I’d like to introduce you to is <strong>comments</strong>. Comments are like documentation within your code — anything you put in a comment is not interpreted by the interpreter. They are <em>essential </em>to ensuring code readability. In the real world, you’ll see a mix of styles and standards, but it’s good to get in the habit of writing comments.</p><p>In Python, you can write a comment in multiple different ways, as seen below:</p><pre># This is a single line comment<br><br>&#39;&#39;&#39; You can use three single-ticks for single line comments... &#39;&#39;&#39;<br><br>&#39;&#39;&#39;<br>You can also use them for...<br>multi-line comments!<br>&#39;&#39;&#39;<br><br>&quot;&quot;&quot;<br>Double quotes<br>also work<br>for multi-line<br>comments<br>&quot;&quot;&quot;</pre><p>Let’s begin by documenting what our code is going to do. Again, this is a simple calculator app… so our description should probably have something to do with that:</p><pre>&#39;&#39;&#39;<br>This script will allow users to run a simple<br>calculator app with supplied arguments on the <br>command line.<br>&#39;&#39;&#39;</pre><p>Now, I know this may seem a little overkill for such a simple app, but when you start working in larger projects, have an idea of what a piece of code is doing is vital to team collaboration.</p><p>Below this, let’s document the author and the version of the code:</p><pre>__author__ = &quot;Drowsy Dev&quot;<br>__version__ = 1.0</pre><p>This is our first look at <strong>variables</strong>. A variable in programming is simply an object or container that stores some information. In the above example, we set the variable __author__ to Drowsy Dev . Now, any time we reference __author__ , the code knows we mean Drowsy Dev . This is called <strong>variable assignment</strong>.</p><p>The variables above are special variables often referred to as dunder variables (double underscore). Anytime you see a variable with double underscores before and after the actual text, just know these are dunder variables. I won’t go too in-depth into these here, but just know these are a standard in Python, and you’ll see them throughout your coding journey. I’ll mention them as we see them in this series.</p><h4>Calculator Functions</h4><p>Now, because we are building a calculator, let’s start with adding the functions for adding, subtracting, multiplying, and dividing. A <strong>function </strong>in programming is just like a function in math — given some input(s) produce some output(s).</p><p>Let’s begin with the addition function:</p><pre>def add(num1: float, num2: float) -&gt; float:<br>    &#39;&#39;&#39;Adds two floats together and return the sum.<br><br>       :param num1: float, The first number to add<br>       :param num2: float, The second number to add<br><br>       :return sum: float, The sum of the supplied arguments<br><br>       Example Usage:<br>       ```<br>        sum = add(1.0, 2.0)<br>        print(sum) # 3.0<br>       ```<br>    &#39;&#39;&#39;<br>    sum = num1 + num2<br>    return sum</pre><p>I know this is a lot, but we’ll walk through it step by step.</p><p>First, we see what’s called the <strong>function definition</strong>:</p><pre>def add(num1: float, num2: float) -&gt; float:</pre><p>The keyword def indicates we are defining a function (keywords are reserved words in a programming language that have special meaning to the compiler or interpreter. Rule of thumb… never make a variable name a keyword unless you want to have a bad time).</p><p>After def we provide the name of the function, in this case, add . Then, we have a set of parenthesis. Inside, we define the <strong>arguments </strong>to the function. Arguments represent what we are passing into the function — think of this like passing in x to a function in math.</p><p>You’ll notice we have two arguments, namely, num1 and num2 . After each of these, we have a colon and the term float . This is called <strong>type annotation </strong>in Python. While not required in Python because the language infers the types of variables for us, it is a good practice and makes code more readable for others. In programming, types denote what kind of variable we are dealing with. Common types include strings, integers, lists, and floats. A float is a number with a decimal (as opposed to an int for whole numbers). Finally, we have an arrow pointing to the type of float again. This is because we are returning a variable of that type from the end of the function. I’ll touch on returns in a moment.</p><p>Below the definition, we have what you’ve hopefully identified as a multi-line comment:</p><pre>&#39;&#39;&#39;Adds two floats together and return the sum.<br><br>       :param num1: float, The first number to add<br>       :param num2: float, The second number to add<br><br>       :return sum: float, The sum of the supplied arguments<br><br>       Example Usage:<br>       ```<br>        sum = add(1.0, 2.0)<br>        print(sum) # 3.0<br>       ```<br>&#39;&#39;&#39;</pre><p>The first part of this comment simply describes what the function does. Next, we define the parameters (another words for the arguments) we are passing into the function. My common standard is as follows:</p><pre>:param &lt;variable name&gt;: &lt;variable type&gt;, &lt;variable description&gt;</pre><p>Below this, I do the same for our return variable.</p><p>Finally, we have an example usage. This is just more documentation that shows an example of how to use the function. If you are using VSCode and have the Python extension installed from earlier, you should be able to hover over the function name and see a nice block of documentation.</p><p>Now, the code of the function. This is probably the simplest part of the whole thing:</p><pre>sum = num1 + num2<br>return sum</pre><p>Again, the first line is variable assignment: we are assigning the variable sum to the value of num1 + num2 , our two arguments passed in. Because the type of both of those variables is float , the Python interpreter will infer that sum also has to be of the type float . Finally, we use the keyword return to denote what we want to return from the function, in this case, the variable sum .</p><p>A function does not have to return a value, but in this case, we want to be able to pass in two numbers and get back their sum. Therefore, we have to return the variable sum. You can return any data type, and even multiple data types, as we’ll see later.</p><p>With addition out of the way, let’s write the other three functions we need for subtraction, multiplication, and division:</p><pre>def subtract(num1: float, num2: float) -&gt; float:<br>    &#39;&#39;&#39;Subtract two floats and return the difference.<br><br>       :param num1: float, The number to subtract from<br>       :param num2: float, The number to subtract<br><br>       :return difference: float, The difference of the supplied arguments<br><br>       Example Usage:<br>       ```<br>        difference = subtract(5.0, 3.0)<br>        print(difference) # 2.0<br>       ```<br>    &#39;&#39;&#39;<br>    difference = num1 - num2<br>    return difference<br><br>def multiply(num1: float, num2: float) -&gt; float:<br>    &#39;&#39;&#39;Multiplies two floats together and return the product.<br><br>       :param num1: float, The first number to multiply<br>       :param num2: float, The second number to multiply<br><br>       :return product: float, The product of the supplied arguments<br><br>       Example Usage:<br>       ```<br>        product = multiply(3.0, 2.0)<br>        print(product) # 6.0<br>       ```<br>    &#39;&#39;&#39;<br>    product = num1 * num2<br>    return product<br><br>def divide(num1: float, num2: float) -&gt; (float | str):<br>    &#39;&#39;&#39;Divides two floats and return the quotient.<br><br>       :param num1: float, The number to divide from<br>       :param num2: float, The number to divide by<br><br>       :return quotient: float, The quotient of the supplied arguments<br><br>       Example Usage:<br>       ```<br>        quotient = divide(6.0, 2.0)<br>        print(quotient) # 3.0<br>       ```<br>    &#39;&#39;&#39;<br>    if num2 == 0:<br>        print(&quot;Error: Divide by zero error&quot;)<br>        return &quot;inf&quot;<br>    quotient = num1 / num2<br>    return quotient</pre><p>Hopefully, most of this makes sense given our breakdown of the addition function. Take your time to read through the code and please feel free to drop any comments on anything that doesn’t make sense.</p><p>You’ll notice something a little different about the divide function. Let’s dive into this.</p><p>One of the tricky parts about division is that you can’t divide by zero. If you tried to do this in Python, you’d get an error:</p><pre>bradley@DESKTOP-4DK7NRH:~$ python3<br>Python 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] on linux<br>Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.<br>&gt;&gt;&gt; 5 / 0<br>Traceback (most recent call last):<br>  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;<br>ZeroDivisionError: division by zero<br>&gt;&gt;&gt; </pre><p>More specifically, we get what’s called an <strong>exception </strong>— an error thrown by the Python interpreter that means we hit some sort of issue while executing the code. I’ll touch on exceptions and how to handle them in a future blog.</p><p>To avoid hitting this error, we use an <strong>if statement:</strong></p><pre>if num2 == 0:<br>    print(&quot;Error: Divide by zero error&quot;)<br>    return &quot;inf&quot;</pre><p>An if statement essentially says: if this statement is true, then run the code inside the block. Otherwise, skip the code and move on. Python blocks are delineated using indents (four spaces):</p><pre>if x == 5:<br>     print(x)<br>print(&quot;Done&quot;)<br><br># If x is equal to 5, we&#39;d print out both 5 and &quot;Done&quot;<br># If x is anything else, we&#39;d just print out &quot;Done&quot;</pre><p>Back to our use case, we check if the second number is zero. If it is, we print out to the user that there is a divide by zero error and return the string “inf” to represent “infinity”.</p><p>If the second number is anything other than zero, we just return the quotient of the division. Because we could either be returning “inf” or the quotient, which would be a float , our return type annotation is (float | str) , representing a return type of either float or string.</p><h4>Making it a Command Line Application</h4><p>So, we’ve got our calculator functions in place (recap on code below):</p><pre>&#39;&#39;&#39;<br>This script will allow users to run a simple<br>calculator app with supplied arguments on the <br>command line.<br>&#39;&#39;&#39;<br><br>__author__ = &quot;Drowsy Dev&quot;<br>__version__ = 1.0<br><br>from argparse import ArgumentParser<br><br>def add(num1: float, num2: float) -&gt; float:<br>    &#39;&#39;&#39;Adds two floats together and return the sum.<br><br>       :param num1: float, The first number to add<br>       :param num2: float, The second number to add<br><br>       :return sum: float, The sum of the supplied arguments<br><br>       Example Usage:<br>       ```<br>        sum = add(1.0, 2.0)<br>        print(sum) # 3.0<br>       ```<br>    &#39;&#39;&#39;<br>    sum = num1 + num2<br>    return sum<br><br>def subtract(num1: float, num2: float) -&gt; float:<br>    &#39;&#39;&#39;Subtract two floats and return the difference.<br><br>       :param num1: float, The number to subtract from<br>       :param num2: float, The number to subtract<br><br>       :return difference: float, The difference of the supplied arguments<br><br>       Example Usage:<br>       ```<br>        difference = subtract(5.0, 3.0)<br>        print(difference) # 2.0<br>       ```<br>    &#39;&#39;&#39;<br>    difference = num1 - num2<br>    return difference<br><br>def multiply(num1: float, num2: float) -&gt; float:<br>    &#39;&#39;&#39;Multiplies two floats together and return the product.<br><br>       :param num1: float, The first number to multiply<br>       :param num2: float, The second number to multiply<br><br>       :return product: float, The product of the supplied arguments<br><br>       Example Usage:<br>       ```<br>        product = multiply(3.0, 2.0)<br>        print(product) # 6.0<br>       ```<br>    &#39;&#39;&#39;<br>    product = num1 * num2<br>    return product<br><br>def divide(num1: float, num2: float) -&gt; (float | str):<br>    &#39;&#39;&#39;Divides two floats and return the quotient.<br><br>       :param num1: float, The number to divide from<br>       :param num2: float, The number to divide by<br><br>       :return quotient: float, The quotient of the supplied arguments<br><br>       Example Usage:<br>       ```<br>        quotient = divide(6.0, 2.0)<br>        print(quotient) # 3.0<br>       ```<br>    &#39;&#39;&#39;<br>    if num2 == 0:<br>        print(&quot;Error: Divide by zero error&quot;)<br>        return &quot;inf&quot;<br>    quotient = num1 / num2<br>    return quotient</pre><p>You can execute the code like so. Pull up the terminal in VSCode. You can do this either by using the Terminal tab in the top menu bar of the editor or using CTRL + J on Windows:</p><pre>bradley@DESKTOP-4DK7NRH:~$ python3 main.py <br>bradley@DESKTOP-4DK7NRH:~$ </pre><p>You should get no errors, but you also won’t see anything happen. This is because we need to actually allow the user to pass in what they want to have happen like add 5 plus 3 or multiply 6 times 8 .</p><p>To do this, we could write all the code from scratch, but there are a ton of packages that provide this functionality out of the box. Python’s <strong>standard library</strong>, a collection of packages provided with your Python installation by default, provides a package called argparse that gives us the ability to build command line (CLI) applications with ease. To bring in the package, we need to create an import statement, which tells Python to essentially bring the code for a package into our source code so we can use it’s functions, classes, etc. You’ll see a few different types of import statements like below:</p><pre># Imports the entire package and all it&#39;s functions, classes, etc.<br>import package<br><br># Imports a specific function, class, or variable from a package<br>from package import my_class, my_function, my_variable<br><br># Imports a package and gives it an alias for easier reference<br>import package as alias</pre><p>For our use case, we just need the ArgumentParser class from argparse . So, let’s import it! Note that import statements should almost always come at the top of the source code, so we’ll put it below our author and version:</p><pre>__author__ = &quot;Drowsy Dev&quot;<br>__version__ = 1.0<br><br>from argparse import ArgumentParser</pre><p>You’ve heard me mention class a few times now, and that’s what ArgumentParser is, so what the heck is a class ? I like to think of a class as a car. A car has attributes like it’s make, model, and year. The car can also do things like drive, stop, and play the radio. In coding terms, the attributes are the <strong>class variables </strong>and the things the car can do like drive and stop are <strong>class functions</strong>. In other words, you can use a class to define some object that provides functions and stores attributes. The class is first defined, like a blueprint, then it can be used via <strong>instantiation </strong>(shown below). We’ll go over classes more in-depth in another blog, but that’s the high-level overview for now.</p><p>So, the argparse library has provided us a class ArgumentParser that we can use to parse command line arguments. To use the class, we instantiate it:</p><pre>parser = ArgumentParser()<br>&#39;&#39;&#39;<br>Note, because we imported `ArgumentParser` directly, we can just called it.<br>If we imported the whole package like `import argparse`, we&#39;d have to do:<br><br>parser = argparse.ArgumentParser()<br>&#39;&#39;&#39;</pre><p>Here, we are assigning the variable parser to an instance of the class ArgumentParser . When doing instantiation, we have to provide the class name and a set of parenthesis. Inside these parenthesis, we can provide variables that dictate how the instance of the class behaves, but for our use case, we can just leave everything as default.</p><p>Now, we add the arguments we want to allow the user to supply:</p><pre>parser.add_argument(&quot;operation&quot;, type=str, <br>                    choices=[&quot;add&quot;, &quot;subtract&quot;, &quot;multiply&quot;, &quot;divide&quot;], <br>                    help=&quot;The operation to run on the given arguments.&quot;)<br>parser.add_argument(&quot;num_one&quot;, type=float, help=&quot;The first number.&quot;)<br>parser.add_argument(&quot;num_two&quot;, type=float, help=&quot;The second number.&quot;)</pre><p>Here, we call the function add_argument on our parser . What does that mean? Well, the add_argument function is a function specifically defined in the ArgumentParser class. To call a function defined for a class in Python, we use the syntax: class_instance.class_function(...) .</p><p>In the above code, we add three <strong>positional </strong>arguments. A positional argument is an argument that has to be supplied in a specific order and is <strong>always </strong>required. The other type of arguments you’ll see are <strong>optional</strong> arguments, typically denoted with -- or - in front of them:</p><pre>python3 myprogram foobar --verbose -o<br><br># foobar --&gt; positional argument<br># --verbose --&gt; optional argument<br># -o --&gt; optional argument</pre><p>Let’s break down the first argument we added:</p><pre>parser.add_argument(&quot;operation&quot;, type=str, <br>                    choices=[&quot;add&quot;, &quot;subtract&quot;, &quot;multiply&quot;, &quot;divide&quot;], <br>                    help=&quot;The operation to run on the given arguments.&quot;)</pre><ul><li>“operation” → The name of the argument</li><li>“type” → Type of the variable being passed in</li><li>“choices” → The valid choices we want to constrain the user to supply</li><li>“help” → The help that will be displayed when the user asks for the commands help</li></ul><p>You’ll notice that choices looks like a list of options. In Python, you’ll create lists using brackets and separate the elements using commas. A list is just that — a collection of elements.</p><p>Now that we’ve defined our options, we need to actually grab them:</p><pre>args = parser.parse_args()<br>operation = args.operation<br>num_one = args.num_one<br>num_two = args.num_two</pre><p>Again, we use another class function, parse_args , to grab the arguments that were supplied by the user. This gives us a class called Namespace that we store in the args variable. Using this instance of the Namespace class, we can access our three arguments using that similar dot notation we’ve been using for functions.</p><p>Finally, we can supply our arguments to the amazing code we wrote earlier using a simple set of if statements:</p><pre>result = None<br>if operation == &quot;add&quot;:<br>    result = add(num_one, num_two)<br>elif operation == &quot;subtract&quot;:<br>    result = subtract(num_one, num_two)<br>elif operation == &quot;multiply&quot;:<br>    result = multiply(num_one, num_two)<br>else:<br>    result = divide(num_one, num_two)</pre><p>NOTE: None is a reserved keyword that represents… well nothing. We use it as a placeholder, then reassign it with the value from whichever function we end up calling.</p><p>You’ll notice that here we have an elif statement too. This stands for else if . Some simple control flow you’ll see in Python includes if , elif , and else . As we touched on earlier, if means ‘if this statement is true, run the code in this block’. The elif statement <em>always </em>comes after an if statement and means ‘if the above statement was not true, <em>and </em>this statement is true, run this block of code’. Finally, the else statement <em>always </em>comes after an if statement, and it means ‘if everything above me was false, run this block of code’.</p><p>Looking at our above code block should bring a little more light to this control flow idea — we first check if the operation selected was add. If the user supplied add , we’ll execute the add function then move on. Else, if the user supplies subtract , we won’t execute the add function because that first if statement was false (“subtract” does not equal “add”), and we’ll execute the subtract function. Same goes for the multiply function. If none of those three options are supplied, because we constrain the user to supply one of “add”, “subtract”, “multiply”, or “divide” with our choices option earlier, we know for a fact the only remaining option is “divide”, therefore, we can execute the divide function.</p><p>Finally, at the very end we print the result:</p><pre>print(f&quot;Result: {result}&quot;)</pre><p>Here, we use the built-in print function to print out what is inside the parenthesis. you’ll notice we use a special kind of string called an f-string. This is denoted by the f before the quotations. This allows us to insert a code inside our string like a variable or an expression. In this case, we insert the result variable.</p><p>The final source code should look like so:</p><pre>&#39;&#39;&#39;<br>This script will allow users to run a simple<br>calculator app with supplied arguments on the <br>command line.<br>&#39;&#39;&#39;<br><br>__author__ = &quot;Drowsy Dev&quot;<br>__version__ = 1.0<br><br>from argparse import ArgumentParser<br><br>def add(num1: float, num2: float) -&gt; float:<br>    &#39;&#39;&#39;Adds two floats together and return the sum.<br><br>       :param num1: float, The first number to add<br>       :param num2: float, The second number to add<br><br>       :return sum: float, The sum of the supplied arguments<br><br>       Example Usage:<br>       ```<br>        sum = add(1.0, 2.0)<br>        print(sum) # 3.0<br>       ```<br>    &#39;&#39;&#39;<br>    sum = num1 + num2<br>    return sum<br><br>def subtract(num1: float, num2: float) -&gt; float:<br>    &#39;&#39;&#39;Subtract two floats and return the difference.<br><br>       :param num1: float, The number to subtract from<br>       :param num2: float, The number to subtract<br><br>       :return difference: float, The difference of the supplied arguments<br><br>       Example Usage:<br>       ```<br>        difference = subtract(5.0, 3.0)<br>        print(difference) # 2.0<br>       ```<br>    &#39;&#39;&#39;<br>    difference = num1 - num2<br>    return difference<br><br>def multiply(num1: float, num2: float) -&gt; float:<br>    &#39;&#39;&#39;Multiplies two floats together and return the product.<br><br>       :param num1: float, The first number to multiply<br>       :param num2: float, The second number to multiply<br><br>       :return product: float, The product of the supplied arguments<br><br>       Example Usage:<br>       ```<br>        product = multiply(3.0, 2.0)<br>        print(product) # 6.0<br>       ```<br>    &#39;&#39;&#39;<br>    product = num1 * num2<br>    return product<br><br>def divide(num1: float, num2: float) -&gt; (float | str):<br>    &#39;&#39;&#39;Divides two floats and return the quotient.<br><br>       :param num1: float, The number to divide from<br>       :param num2: float, The number to divide by<br><br>       :return quotient: float, The quotient of the supplied arguments<br><br>       Example Usage:<br>       ```<br>        quotient = divide(6.0, 2.0)<br>        print(quotient) # 3.0<br>       ```<br>    &#39;&#39;&#39;<br>    if num2 == 0:<br>        print(&quot;Error: Divide by zero error&quot;)<br>        return &quot;inf&quot;<br>    quotient = num1 / num2<br>    return quotient<br><br>parser = ArgumentParser()<br>parser.add_argument(&quot;operation&quot;, type=str, <br>                    choices=[&quot;add&quot;, &quot;subtract&quot;, &quot;multiply&quot;, &quot;divide&quot;], <br>                    help=&quot;The operation to run on the given arguments.&quot;)<br>parser.add_argument(&quot;num_one&quot;, type=float, help=&quot;The first number.&quot;)<br>parser.add_argument(&quot;num_two&quot;, type=float, help=&quot;The second number.&quot;)<br><br>args = parser.parse_args()<br>operation = args.operation<br>num_one = args.num_one<br>num_two = args.num_two<br><br>result = None<br>if operation == &quot;add&quot;:<br>    result = add(num_one, num_two)<br>elif operation == &quot;subtract&quot;:<br>    result = subtract(num_one, num_two)<br>elif operation == &quot;multiply&quot;:<br>    result = multiply(num_one, num_two)<br>else:<br>    result = divide(num_one, num_two)<br><br>print(f&quot;Result: {result}&quot;)</pre><p>Now, you can test our your final CLI calculator using the terminal once again:</p><pre>bradley@DESKTOP-4DK7NRH:~$ python3 main.py add 5 3<br>Result: 8.0<br>bradley@DESKTOP-4DK7NRH:~$ python3 main.py multiply 5 3<br>Result: 15.0<br>bradley@DESKTOP-4DK7NRH:~$ python3 main.py subtract 5 3<br>Result: 2.0<br>bradley@DESKTOP-4DK7NRH:~$ python3 main.py divide 5 3<br>Result: 1.6666666666666667</pre><p>Congrats! You’ve written your very first CLI Python application! I know the actual function is very simple, but you hopefully pulled away a lot of foundational coding and Python knowledge from this blog. As I always say, project based learning is the best way to pick up something new. Go forth, write more code, and I’ll see you in the next one!</p><p>Source code available here: <a href="https://github.com/TheDrowsyDev/PythonCLICalculator">https://github.com/TheDrowsyDev/PythonCLICalculator</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a73a23d799fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>