<?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[Makimo On Software Development - Medium]]></title>
        <description><![CDATA[Makimo is a bespoke software development company located in Lodz, Poland with main focus on consultancy, custom software development and legacy software modernization. Here we share what we know, learn, discover or struggle with when we craft our software. - Medium]]></description>
        <link>https://medium.com/makimo-on-software-development?source=rss----98fc48642ba7---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Makimo On Software Development - Medium</title>
            <link>https://medium.com/makimo-on-software-development?source=rss----98fc48642ba7---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 19:35:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/makimo-on-software-development" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[MVP in Python for startups — a suitable choice?]]></title>
            <link>https://medium.com/makimo-on-software-development/mvp-in-python-for-startups-a-suitable-choice-32cc4d124bac?source=rss----98fc48642ba7---4</link>
            <guid isPermaLink="false">https://medium.com/p/32cc4d124bac</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Michał Moroz]]></dc:creator>
            <pubDate>Tue, 16 May 2023 13:59:44 GMT</pubDate>
            <atom:updated>2023-05-16T13:59:44.523Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h3><strong>MVP in Python for startups — a suitable choice?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pOIqrpU9Cw0uJIh1LhNHTg.png" /></figure><p>One of the early steps of building a software product is choosing the right technology for the task. That way, one can leverage this right choice for cost optimization or ease of further development, thus speeding up the tempo of product development. Both of these positive outcomes improve the product’s time to market.</p><p>The questions are:</p><ul><li>Is Python a viable platform for an MVP?</li><li>What are the right choices for using Python in MVP development?</li></ul><h3>What is an MVP?</h3><p>An MVP is an abbreviation for Minimum Viable Product, a version of the application with only the most critical features available. That formulation of the problem helps to validate startup ideas and see their market potential. Ideally, the application has as few features as possible yet is rock-solid in what it does. At this stage, it’s safe to assume that nobody understands the software product’s future direction.</p><p>For the consumers of the software product, it means the software product they will use is limited in functionality but not in quality. That’s an important distinction, as customers care about the software being reliable from day one, even if that software doesn’t suit them 100%. It’s better to have a delightful experience and a small product than an application with many features but a frustrating experience.</p><p>In one of the rules of thumb I use in <a href="https://makimo.pl/">Makimo</a>, MVP applications approximate 1000 hours of work, which means that you would expect a working prototype in 2–4 months, depending on the level of preparation and discovery at the start of cooperation.</p><h3>Methodology</h3><p>Recently I’ve analyzed 224 repositories of code, 50 of which were written using Python. These contain the commercial and internal projects we’ve been working on in recent years, following our transition from BitBucket to GitHub in early 2020.</p><p>This is an ongoing project of mine to gain more insight into the types and shapes of technological solutions we provide to our customers.</p><p>For the sake of this article, I chose a no-framework approach. Instead of defining project categories from the top down, I sought to discover them as I gathered more information. Here’s what I found.</p><h3>Is Python suitable for an MVP?</h3><p>The short answer is — yes. We’ve written enough commercial applications to reach that conclusion. Python is our language of choice for most new projects we use. We’ve confirmed the feasibility of that for the following industries:</p><ul><li>Data processing and analysis, including AI/ML programming</li><li>Portals and web applications for record storage and management</li><li>Integrations with other software platforms</li><li>Custom eCommerce platforms (see the case study)</li><li>Big data analytics</li><li>Financial applications</li><li>Industrial data processing</li><li>Knowledge management and document processing</li><li>APIs and backend applications for mobile applications</li><li>Visualizations and scoring systems in sports</li></ul><p>From that, I can tell that I’m confident that Python is a strong general choice, with practical uses in web applications, data processing, and AI. It’s also one of the more popular languages in use, which is also a bonus, as it reduces the risk of a limited talent pool.</p><p>Now, let’s explore options available that leverage Python as the right choice. The next sections describe a selection of the potential uses that you might find interesting.</p><h3>Django MVP — record management</h3><p>One of the oldest and most mature web frameworks to date and one I’ve been deeply involved with from its inception. I wrote my first commercial <a href="https://www.djangoproject.com/">Django</a> application using version 0.9.6 in 2008. As of 2023, the stable version is 4.1.6.</p><p>The strength of this solution lies in its ability to manage records. There are lots and lots of facilities for all kinds of structured data, and we’ve used it most successfully in small to medium-traffic applications that manage different types of data in a database.</p><p>The main uses of Django are:</p><ul><li>web portals, especially with non-typical kinds of data — as an example, a university portal <a href="https://fizyka.p.lodz.pl/en/">https://fizyka.p.lodz.pl/en/</a> storing a catalog of scientific publications of its staff</li><li>document management, knowledge management, data management, and dashboards</li><li>electronic document circulation and document workflows (e.g., mediation platforms)</li><li>ERPs and resource management applications</li><li>internal web applications</li><li>back end applications for mobile devices</li></ul><p>The advantages of Django are:</p><ul><li>record-storing and editing</li><li>a “free” administration panel for record management</li><li>facilities for batch editing records</li><li>SEO friendliness</li><li>quickly building APIs for record management</li></ul><p>The definition of record management can be stretched very far and to high loads — it’s worth saying that parts of Instagram and Pinterest are written using the Django framework.</p><p>As a web framework architecturally built around the idea of record management, it has a few disadvantages, too. Django really embraces a development style where the application being built has a single, strong purpose and a reason for being. That’s great for MVP, a little less so for complex corporate business applications where a lot of business goals intermingle with each other, and multiple teams are working on satisfying these goals.</p><p>The second disadvantage is when you need to handle rich, real-time updates for parts of the application. A good example here is reactive systems for industrial event processing. For that purpose, we’ve started experimenting with the Elixir language and Phoenix framework, and it seems to be a good fit.</p><p>A note worth mentioning is that all of these can be managed by a mature team of developers and setting the right architectural drivers early in the development.</p><h3>Flask + Microservices Architecture MVP = complex, multi-purpose applications</h3><p>A few years ago, we started experimenting with more scalable approaches to development. The design we’ve arrived at is a combination of three elements:</p><ol><li><a href="https://flask.palletsprojects.com/en/2.3.x/">Flask</a> applications for backend development and API</li><li><a href="https://microservices.io/patterns/data/database-per-service.html">Database per service pattern</a> — enabling on-demand microservice decomposition</li><li>Frontend and mobile applications use these APIs and present multiple interfaces (e.g., admin, buyer, seller, mobile) to the end users.</li></ol><p>The main uses of such architecture are:</p><ul><li>Financial applications, including transactional management, payment processing, auctions, trading, or all of the above</li><li>Multi-tenant applications (for B2B clients) with feature differences between clients</li><li>Workflow automation and business process optimization</li><li>eCommerce platforms – <a href="https://makimo.pl/blog/vendor-saas-ecommerce-start-up-mvp-software-development/">see a case study</a></li><li>Scalable API designs for both frontend and mobile applications</li><li>Composable architecture</li></ul><p>The upfront costs for such an application are usually higher than Django, but this architecture scales well, leverages independent teams working on different parts of the system, and can make good use of the rich cloud-native offerings of AWS or other cloud providers.</p><p>Such architecture can work for multiple years, and there are fewer risks that scaling the number of customers would meet a hard-to-overcome limit in system throughput. That also means B2B customers, where the infrastructure, features, or integrations need to be customized for each of them.</p><p>If I were working on a complex or <a href="https://makimo.pl/blog/towards-composable-architecture-the-importance-of-the-api/">composable architecture</a> that needs to satisfy multiple business goals and stakeholders, Flask would be my choice, even for the MVP stage. For record management, I’d still go with Django.</p><p>When it comes to the cost of such an application, I would add some markup to the rule of thumb I stated earlier. It’s hard to say how much. When it comes to such multi-purpose, multi-stakeholder applications, we’re entering an area where the cost depends on too many factors to provide sensible numbers without analysis.</p><p>I would also discuss with the potential client how to satisfy at least one group of stakeholders as soon as possible so that the <a href="https://makimo.pl/blog/how-to-measure-the-value-of-software/">application will start delivering value</a> even if it’s not anywhere near its completion.</p><h3>Tensorflow, YOLO, and similar libraries — Artificial Intelligence and Machine Learning</h3><p>AI recently has sure processed many people’s expectations — and it’s a hot topic nowadays. We’ve been using Python AI libraries to enhance the capabilities of what traditional software development can do and have been satisfied with the results so far.</p><p>The main uses of such solutions are:</p><ul><li>Decision support systems — learning from past data</li><li>Computer vision applications, such as waste reduction in manufacturing processes</li><li>Analysis of large unstructured sets of data</li><li>Natural language processing</li></ul><p>Python’s programming language makes it fast to develop such solutions due to its relative simplicity in writing programs and extensive support from major players in the AI industry. It also integrates well with other uses found in this article — so you can build an internal application that processes data, integrates it with other services, and does machine learning on it.</p><h3>Data processing, Pandas, and integrations — data automation</h3><p>The last major use of Python language is what I call the glue between other systems and applications. For example, it’s easy to develop a module integrating an eCommerce API with another API that handles marketing automation.</p><p>The main uses here are:</p><ul><li>service integrations, enabling business composability on top of already existing APIs</li><li>automatic processing of spreadsheet data — providing summaries and report generation</li><li>getting data from thousands of surveys, handling missing data</li><li>extracting useful insights from big sets of data</li><li>automating workflows</li></ul><p>The advantages of Python for startups when it comes to automation are the following:</p><ul><li>reducing initial MVP costs by using other services and integrating them to produce value</li><li>quick prototyping, often faster than in other languages due to good data analysis packages (Pandas, Anaconda)</li><li>reduction of repetitive tasks, allowing startup teams to focus on something else.</li></ul><p>The prototyping aspect here is a benefit that shouldn’t be missed. In my career, I’ve written a lot of scripts automating certain tasks, which took me a couple of hours or days each. Even for this article, I’ve used Python to automate the discovery process, show me all the projects we’ve been working on recently, and generate a summary that was a big help in writing this article.</p><h3>Conclusion — Is Python a suitable candidate for a startup’s MVP development?</h3><p>MVPs in Python are possible. The language and its ecosystem are mature and popular enough that its applications are a good choice across industries and across disciplines. From data science to building backend applications, the language is a good overall choice when it comes to building systems for many industries and purposes.</p><p>Python is certainly not a one-stop shop for all developers alike. For frontend developers, JavaScript or TypeScript is used, and there are a lot more languages available for backend development, too — all with their pros and cons. I hope this article will shed some light on one of the technologies and possible business use cases for them.</p><p>And if you didn’t find your particular case in the examples above, be assured that there are other options as well as those mentioned in this article. Do not hesitate to contact me then. I’m easily available for a chat at my e-mail address: <a href="/service/mailto:michal@makimo.pl">michal@makimo.pl</a>, and I will gladly answer any of your questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32cc4d124bac" width="1" height="1" alt=""><hr><p><a href="https://medium.com/makimo-on-software-development/mvp-in-python-for-startups-a-suitable-choice-32cc4d124bac">MVP in Python for startups — a suitable choice?</a> was originally published in <a href="https://medium.com/makimo-on-software-development">Makimo On Software Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upgrading PostgreSQL’s Enum type with SQLAlchemy using Alembic migration]]></title>
            <link>https://medium.com/makimo-on-software-development/upgrading-postgresqls-enum-type-with-sqlalchemy-using-alembic-migration-881af1e30abe?source=rss----98fc48642ba7---4</link>
            <guid isPermaLink="false">https://medium.com/p/881af1e30abe</guid>
            <category><![CDATA[alembic]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[sqlalchemy]]></category>
            <dc:creator><![CDATA[Kamil Kucharski]]></dc:creator>
            <pubDate>Wed, 23 Dec 2020 11:34:48 GMT</pubDate>
            <atom:updated>2020-12-23T11:34:48.322Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*oNvoyVoOOThlDhGTv06uhg.jpeg" /></figure><p>Alembic is an awesome library to setup migrations for your database schema which works really great. There is one small thing which it isn’t capable of though. When you upgrade an enum value in your code, it may get pretty confused.</p><p>This tutorial will show you how to overcome this weakness, so you don’t get stuck with upgrading the enum types yourself on the PostgreSQL server, but rather create the migration file which will do that for you.</p><h3>Basic model</h3><p>Let’s jump straight into the code. Let’s say we have the following enum and SQLAlchemy’s ORM model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f66a992f63c8962fd9370f1f4d8d4b7/href">https://medium.com/media/6f66a992f63c8962fd9370f1f4d8d4b7/href</a></iframe><p>Then, generating Alembic’s new revision will result in the migration file containing our status field details with available values imprinted:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbcdafa3c4aa5410bcd9c93ee2567382/href">https://medium.com/media/fbcdafa3c4aa5410bcd9c93ee2567382/href</a></iframe><h3>Updating the enum</h3><p>What will happen if we want to add a new status to the enum definition? Let’s try and add one to our Statusenum.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbaed1ef3ca2a1e0773779988ab0c8ac/href">https://medium.com/media/dbaed1ef3ca2a1e0773779988ab0c8ac/href</a></iframe><p>Now, after creating next revision, migration file is going to be empty i.e. it will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01156b3927f681cf416261114aa00f8b/href">https://medium.com/media/01156b3927f681cf416261114aa00f8b/href</a></iframe><p>So, how can we make sure the REJECTED value is added so the database knows that it should be a valid one? Fortunately for us in PostgreSQL 9.1 an ALTER TYPEdirective was added. With it, we can easily upgrade our enum type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/936f699e02e2a38d7ec712d8ef6d4df8/href">https://medium.com/media/936f699e02e2a38d7ec712d8ef6d4df8/href</a></iframe><p>And what about downgrade to roll back the changes? In this case it would be a bit more work, but nothing that couldn’t be done:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc2540b2c0b8a4e66a16d2c6604581a9/href">https://medium.com/media/bc2540b2c0b8a4e66a16d2c6604581a9/href</a></iframe><p>This is still pretty easy, isn’t it?</p><h3>Autocommit block</h3><p>As you’ve probably noticed in the examples above I’ve executed all of the commands inside the autocommit block. Why is that?</p><blockquote>If ALTER TYPE ... ADD VALUE (the form that adds a new value to an enum type) is executed inside a transaction block, the new value cannot be used until after the transaction has been committed.</blockquote><blockquote><a href="https://www.postgresql.org/docs/13/sql-altertype.html">https://www.postgresql.org/docs/13/sql-altertype.html</a></blockquote><p>As you can see from the documentation excerpt it’s necessary to run those commands within the autocommit block. Otherwise if our next migrations will try to use the new value (e.g. to insert new values to the database inside the migration) it will raise an exception as our updated type won’t be available until all migration files are properly executed.</p><p>Furthermore if you are using an older version of PostgreSQL (&lt;12) you will have to add an autocommit block every time when using ALTER TYPE … ADD VALUE command, otherwise the migration will fail. The restriction is needed because using this directive may lead to possible index issues in the enum column.</p><h3>Conclusion</h3><p>In this tutorial we’ve successfully generated the migration file which can automatically upgrade enum types on PostgreSQL server. If you want to read more about this topic or Alembic migrations in general, take a look at an <a href="https://alembic.sqlalchemy.org/en/latest/">official Alembic documentation</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=881af1e30abe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/makimo-on-software-development/upgrading-postgresqls-enum-type-with-sqlalchemy-using-alembic-migration-881af1e30abe">Upgrading PostgreSQL’s Enum type with SQLAlchemy using Alembic migration</a> was originally published in <a href="https://medium.com/makimo-on-software-development">Makimo On Software Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Tale of Three Warriors]]></title>
            <link>https://medium.com/makimo-on-software-development/the-tale-of-three-warriors-7130181fde8f?source=rss----98fc48642ba7---4</link>
            <guid isPermaLink="false">https://medium.com/p/7130181fde8f</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[task-management]]></category>
            <category><![CDATA[time-management]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[command-line-interface]]></category>
            <dc:creator><![CDATA[Marcin Struś]]></dc:creator>
            <pubDate>Thu, 07 Nov 2019 16:21:12 GMT</pubDate>
            <atom:updated>2019-11-07T17:03:06.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qMGXCy6SWPOT9PH8hJTOww.png" /></figure><p>Sometimes managing tasks assigned to a person can be hard. How to list all pending tasks? How to track what are you doing at the moment? How to choose the next task one should start progress? In some cases (especially when your clients are billed on a time basis), proper time tracking is crucial. Furthermore, many companies use tools like Jira or Trello to manage tasks and plan work for the team. While it may be great to perform planning and analysis on the team level, it may be a bit overwhelming for the team members to track their assigned tasks. Being a heavy command-line user, I have stumbled upon a set of tools that address these issues and provide a pleasant interface for handling tasks assigned to me. Ladies and gentlemen, let me introduce the three warriors: taskwarrior, timewarrior and bugwarrior.</p><h3>Managing tasks with taskwarrior</h3><p>The central part of the toolset is taskwarrior application. It can be easily <a href="https://taskwarrior.org/download/">installed on most platforms</a>. This application allows the user to store and maintain a list of tasks. Each task is described by a set of attributes like description, status, project, or priority. The user may also define his own user-defined attributes if needed. To improve filtering, the task may be assigned a set of tags.</p><h3>Managing tasks</h3><p>Creating a task is straightforward:</p><pre>$ task add project:medium Write article about taskwarrior<br>Created task 1.<br>The project &#39;medium&#39; has changed.  Project &#39;medium&#39; is 0% complete (1 task remaining).</pre><p>This command will create a task with the description “Write article about taskwarrior” and assign it in the project medium. As you may have noticed, every task is assigned a numeric ID. This number is used as a handle for the user to perform operations on the tasks. For instance, to modify the newly created task and set high priority use:</p><pre>$ task 1 modify priority:H<br>Modifying task 1 &#39;Write article about taskwarrior&#39;.<br>Modified 1 task.<br>Project &#39;medium&#39; is 0% complete (1 task remaining).</pre><p>To display detailed information about the task use:</p><pre>$ task 1 info<br>Name          Value<br>ID            24<br>Description   Write article about taskwarrior<br>Status        Pending<br>Project       medium<br>Entered       2019-11-02 13:09:47 (7min)<br>Last modified 2019-11-02 13:15:35 (1min)<br>Virtual tags  PENDING READY UDA UNBLOCKED LATEST PROJECT PRIORITY UUID          cc083469-21f3-43f5-ade6-1ffad8969fc5<br>Urgency       7<br>Priority      H</pre><pre>project           1 * 1 = 1<br>   UDA priority.H    1 * 6 = 6<br>                        ------<br>                             7</pre><pre>Date                Modification<br>2019-11-02 13:15:35 Priority set to &#39;H&#39;.</pre><p>To add tag publishing the created task use:</p><pre>$ task 1 modify +publishing<br>Modifying task 1 &#39;Write article about taskwarrior&#39;.<br>Modified 1 task.<br>Project &#39;medium&#39; is 0% complete (1 task remaining).</pre><p>To list all tasks use:</p><pre>$ task list</pre><pre>ID Age   P Project Description                     Urg<br>1  13min H medium  Write article about taskwarrior 7</pre><pre>1 task</pre><p>Every command which refers to existing tasks (like modify, list or delete) may accept filter specification instead of numeric ID. For instance, to list all tasks related to project medium use:</p><pre>$ task project:medium list</pre><pre>ID Age   P Project Tags       Description                     Urg<br>1  22min H medium  publishing Write article about taskwarrior 7.8</pre><pre>1 task</pre><p>Finally, to delete a task use:</p><pre>$ task 1 delete<br>Delete task 24 &#39;Write article about taskwarrior&#39; ? (yes/no) yes Deleting task cc083469 &#39;Write article about taskwarrior&#39;.<br>Deleted 1 task.<br>The project has changed. Project &#39;medium&#39; is 0% complete (0 of 0 tasks remaining).</pre><h3>Managing task status</h3><p>Once our tasks are stored in the database, we should start doing them. To mark a task as being currently worked on use the following command:</p><pre>$ task 1 start<br>Starting task cc083469 &#39;Write article about taskwarrior&#39;.<br>Started 1 task.<br>Project &#39;medium&#39; is 0% complete (1 task remaining).</pre><p>This command will mark the task as active and record the start time as a task attribute. The task will also be marked in the task list.</p><p>Stopping progress is also straightforward:</p><pre>$ task 1 stop<br>Stopping task cc083469 &#39;Write article about taskwarrior&#39;.<br>Stopped 1 task.<br>Project &#39;medium&#39; is 0% complete (1 task remaining).</pre><p>When the task is completed, it should be marked as done. To do this, use the command:</p><pre>$ task 1 done<br>Completed task cc083469 &#39;Write article about taskwarrior&#39;. <br>Completed 1 task.<br>The project has changed. Project &#39;medium&#39; is 100% complete (0 of 1 tasks remaining).</pre><p>Note that taskwarrior is reporting the completion percentage of a project containing the modified projects.</p><p>One nice feature of the taskwarrior is the ability to display the task which should be taken care next, based on the priorities and due dates of all recorded tasks. This is achieved with:</p><pre>$ task next</pre><h3>Tracking time with timewarrior</h3><p>The second tool is <a href="https://timewarrior.net/">timewarrior</a>. The main functionality is to track the time spent on some activities. Each recorded time block can be assigned with a tag. To start tracking time block with tag &quot;Writing Medium article&quot; use:</p><pre>timew start Writing Medium article<br>Tracking Writing article<br>Started 2019-11-02T16:30:18<br>Current                  18<br>Total               0:00:00</pre><p>To stop tracking simply type:</p><pre>$ timew stop<br>Recorded Writing article<br>Started 2019-11-02T16:30:18<br>Ended                 31:47<br>Total               0:01:29</pre><p>Using timewarrior alone might seem a bit inconvenient: you have to manually type tags to match the task started by taskwarrior. However, there is a powerful mechanism provided by the taskwarrior: hooks. Hooks are simple programs (they might be shell scripts, scripts in your favorite scripting language, or even compiled programs) that are run on specific events (for instance: task modification). Input data, i.e. information about modified tasks are fed to the hook with standard input and taskwarrior is expecting it to output modified task data and some status text. More on this may be found in <a href="https://taskwarrior.org/docs/hooks.html">official hooks documentation</a>. The timewarrior package provides the hook for taskwarrior which will start time tracking with timewarrior whenever a task is started and stop it when the task is stopped or marked as done. After installation the task start command will output additional information:</p><pre>$ task 1 start<br>Starting task 0f036218 &#39;Write article about taskwarrior&#39;.<br>Started 1 task.<br>Tracking &quot;Write article about taskwarrior&quot; medium<br>Started 2019-11-02T16:55:15<br>Current                  15<br>Total               0:00:00<br>You have more urgent tasks. Project &#39;medium&#39; is 0% complete (1 task remaining).</pre><p>Checking the current time tracking in timewarrior would give the following result:</p><pre>$ timew<br>Tracking &quot;Write article about taskwarrior&quot; medium<br>Started 2019-11-02T16:55:15<br>Current               56:38 <br>Total               0:01:23</pre><p>And when the task is completed:</p><pre>$ task 1 done<br>Completed task 0f036218 &#39;Write article about taskwarrior&#39; . Completed 1 task.<br>Recorded &quot;Write article about taskwarrior&quot; medium<br>Started 2019-11-02T16:55:15<br>Ended                 58:20<br>Total               0:03:05<br>The project has changed. Project &#39;medium&#39; is 100% complete (0 of 1 tasks remaining).</pre><p>This gives us a really nice time tracking for our tasks. The output of timewarrior is ready to be reported to our employers whenever the task is complete.</p><p>One nice feature of the timewarrior is the possibility to define work hours: for instance from 9 AM to 5 PM. This will tell timewarrior that all active time trackings should be stopped at 5 PM and resumed a 9 AM the next day (unless the user interrupts them manually). Imagine the situation that you start some task at 4:30 PM and finish it the next day. Also, imagine that you have forgotten to stop it manually. Without the working days defined, the time tracking would be ruined and would require manual adjustments. Fortunately, the timewarrior would be smart enough to know when you usually leave the office.</p><h3>Synchronizing tasks from external systems with bugwarrior</h3><p>The last tool I wanted to describe in this article is <a href="https://bugwarrior.readthedocs.io/en/latest/">bugwarrior</a>. It is also the tool the user has almost no interaction with. This tool is used to pull the tasks from external systems like Jira, Trello, GitHub, etc. (the full list can be found <a href="https://bugwarrior.readthedocs.io/en/latest/services.html">here</a>) and insert them into taskwarrior database. It also tracks the imported issues to prevent from inserting duplicates and update already imported tasks.</p><p>The synchronization process is performed by a script called bugwarrior-pull which reads the configuration stored in.bugwarriorrc file to determine which services to contact. Furthermore, every contacted service adds some UDAs to the imported tasks, for instance: Jira service adds a field which stores the Jira ID of the imported issue. It is recommended to run bugwarrior-pull script periodically in the background. Example configuration, which is used by me to synchronize the tasks assigned to me in <a href="https://makimo.pl/">our company</a> Jira and my GitHub issues, can be found in my <a href="https://github.com/Struchu/dotfiles/blob/master/bugwarriorrc">dotfiles</a>.</p><h3>Conclusion</h3><p>The purpose of this article was to provide some quick introduction for taskwarrior, timewarrior and bugwarrior and how they may be utilized to effectively and unobtrusively manage tasks. Note that there are several functionalities that were not mentioned, especially customization, syncing your tasks within several devices and reporting features of the taskwarrior. All those features are described in excellent <a href="https://taskwarrior.org/docs/">documentation</a>. Please also note that these tools are not in any way replacement for tools like Jira when planning and analyzing the work for the team as a whole is considered (for instance: sprint planning or estimating the remaining workload in the project). The warriors are great at managing tasks at the team member level and nothing more<em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7130181fde8f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/makimo-on-software-development/the-tale-of-three-warriors-7130181fde8f">The Tale of Three Warriors</a> was originally published in <a href="https://medium.com/makimo-on-software-development">Makimo On Software Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hiccup Lightning Tutorial]]></title>
            <link>https://medium.com/makimo-on-software-development/hiccup-lightning-tutorial-6494e477f3a5?source=rss----98fc48642ba7---4</link>
            <guid isPermaLink="false">https://medium.com/p/6494e477f3a5</guid>
            <category><![CDATA[html]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[lisp]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[clojure]]></category>
            <dc:creator><![CDATA[Iwo Herka]]></dc:creator>
            <pubDate>Sun, 15 Sep 2019 16:03:51 GMT</pubDate>
            <atom:updated>2019-10-13T14:25:54.583Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FMlHUW4VO-j_bEWr6C6wkw.png" /></figure><p>Hiccup is a Clojure DSL for writing HTML. Here is a quick tutorial for the busy. It contains most of the information you’re going to need in a typical project.</p><h3>Introduction</h3><p><a href="https://github.com/weavejester/hiccup">Hiccup</a> is a <a href="https://en.wikipedia.org/wiki/Domain-specific_language">domain-specific language</a> for generating HTML in Clojure. In other words, it turns Clojure into HTML. Let’s look at an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df062c8b850f88b27aee723f95838ed1/href">https://medium.com/media/df062c8b850f88b27aee723f95838ed1/href</a></iframe><p>As you can see, it uses literal data structures — in fact, it’s just Clojure’s vectors containing keywords (representing tags) and maps (for HTML properties). The above example compiles down to:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcf49211ce507b78623a0459706c6485/href">https://medium.com/media/dcf49211ce507b78623a0459706c6485/href</a></iframe><p>…which is simple <em>div </em>with a single button which increments some atom counter. Everything is represented as a plain Clojure data-structure.</p><h3>The advantages</h3><ol><li>No need to create separate files for templates. Hiccup is typically used in Reagent/re-frame projects, where views are just Clojure functions returning HTML (or functions returning functions).</li><li>HTML represented as plain vectors which can be easily processed and generated using all the tools of the host language. This means that repetitive code can be abstracted away into functions and mechanically manipulated.</li><li>A thin layer of abstraction allows improving HTML semantics while not being new enough to require re-learning.</li></ol><h3>The gist of it</h3><h4>Vectors and maps</h4><p>If you’re building front-end using Reagent/re-frame, you will probably spend most of the time using Hiccup’s literals. In Hiccup, HTML nodes are represented as Clojure’s vectors. The first element of the vector is always a keyword (e.g. :div) designating HTML tag. Immediately after the tag, we specify special options which act as a syntactic sugar (explained below). The second argument is an optional map of the tag’s attributes. We will specify here things such as inline styles, classes, event listeners, and so on. Lastly, we pass arguments to the element itself, such as a string for the label. Putting it all together, we have:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f37d10fc8463740cd5f79f2cd81655d/href">https://medium.com/media/2f37d10fc8463740cd5f79f2cd81655d/href</a></iframe><p>For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d29926de6bdcb06d41e8d9163c1e76f9/href">https://medium.com/media/d29926de6bdcb06d41e8d9163c1e76f9/href</a></iframe><p><em>Tip</em><strong>: Because Hiccup uses vectors to represent HTML trees, use lists to represent sequences. </strong>Mixing vector sequences with HTML vectors may confuse Hiccup.</p><h4>Constructor functions</h4><p>Hiccup provides constructors for many of the standard HTML elements. Use them to remove some of the boilerplate. For example, instead of slightly verbose:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8ef4c051a24556ccb81c40d5ad6d54d/href">https://medium.com/media/e8ef4c051a24556ccb81c40d5ad6d54d/href</a></iframe><p>…we can do:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5e97ad72eec9459566a238a98dbbf42/href">https://medium.com/media/c5e97ad72eec9459566a238a98dbbf42/href</a></iframe><p>For a comprehensive listing, consult <a href="http://weavejester.github.io/hiccup/index.html">the API documentation</a>.</p><h4>Inline styling</h4><p>Styles can be added on the fly to elements via the :style map:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/115f5394f2096764b34d1715f75700f8/href">https://medium.com/media/115f5394f2096764b34d1715f75700f8/href</a></iframe><p>By default, integers are interpreted as pixels. If you want to use a different unit, use a string instead: {:padding &quot;50rem&quot;}.</p><h4>Sugar for the id and class attribute</h4><p>Hiccup provides a convenient syntax for adding id and class attributes to an element. The following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d24db2802ea51118f9c3f43d8f1e292/href">https://medium.com/media/1d24db2802ea51118f9c3f43d8f1e292/href</a></iframe><p>…can be rewritten as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26a7d13712440af59d8e31be1200935a/href">https://medium.com/media/26a7d13712440af59d8e31be1200935a/href</a></iframe><p>The word after the <em>#</em> denotes the element’s ID, and each word after a dot corresponds to one of the element’s classes. The ID must always come first.</p><p><em>Tip</em>: <strong>Specify permanent classes using sugar and dynamic ones via </strong><strong>:class. </strong>Sometimes you will use a particular class only in certain conditions. For example, the class &quot;active&quot; may depend on the Boolean active?:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddcf6116fb69c4528b468fb7fcce5069/href">https://medium.com/media/ddcf6116fb69c4528b468fb7fcce5069/href</a></iframe><p><em>(Strings to </em><em>:class are concatenated, so we need whitespace to separate classes). </em>My suggestion is to specify classes that are static using sugar notation and leave everything else in the attribute map:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f25cc0f094ac8c91109fd6931ef99045/href">https://medium.com/media/f25cc0f094ac8c91109fd6931ef99045/href</a></iframe><h4>Conditional rendering</h4><p>nil values are ignored. This means that we don’t have to worry about them slipping into our HTML. For example, Clojure’s function (when test &amp; body) will return body if test is true and nil otherwise. Therefore, we can do:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/784615166e43638133e91ac056f9ff2b/href">https://medium.com/media/784615166e43638133e91ac056f9ff2b/href</a></iframe><p>If is-true? is false, the value of the expression will simply be ignored, and only element a will end up in the output.</p><h4>Sugar for nested tags</h4><p>To avoid repetitive nesting of HTML tags:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ceb454cc7ce4910f921a0e854dd8f7fb/href">https://medium.com/media/ceb454cc7ce4910f921a0e854dd8f7fb/href</a></iframe><p>…you can use the &gt; sugar:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0181d1477feb0183c25aaf6677e02b82/href">https://medium.com/media/0181d1477feb0183c25aaf6677e02b82/href</a></iframe><h4>Escape strings with h to avoid XSS</h4><p>Hiccup concatenates strings without asking questions. Therefore, whenever you receive a string from unsafe sources (such as user form or foreign API) you should escape the string with hiccup.core/h:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a40c784e00045b18824bcd19af93304/href">https://medium.com/media/8a40c784e00045b18824bcd19af93304/href</a></iframe><h4>Abstraction</h4><p>One of the biggest advantages of using Hiccup is the ability to abstract away all the repetitiveness of manual HTML-writing. Instead of typing each li, we can use a loop:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f2002476dea495de1aa736b6fcf4d4f/href">https://medium.com/media/3f2002476dea495de1aa736b6fcf4d4f/href</a></iframe><p>Often, it’s a good idea to write a generator function for a commonly occurring element. For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1c75fc240845535482173d07b71d1e9/href">https://medium.com/media/c1c75fc240845535482173d07b71d1e9/href</a></iframe><p>…which yields a button with an internal counter variable. We can stack and nest those endlessly. However, as <a href="https://purelyfunctional.tv/mini-guide/hiccup-tips/">Eric Normand points out</a>, there is one problem:</p><blockquote>[..] because the Hiccup compiler doesn’t do a full examination of your code, it can’t compile everything. It inserts run time fallbacks for stuff it can’t handle at compile time which will interpret it at run time. So, for instance, <strong>if you’re calling a function that returns some Hiccup, it can’t compile that automatically</strong>. It has to wait till the function returns to know what it is. That is, unless . . .</blockquote><blockquote><strong>The fix:</strong> The way to get Hiccup to compile something is with the <a href="http://weavejester.github.io/hiccup/hiccup.core.html#var-html"><em>hiccup.core/html</em></a> macro. That’s the macro that does the compilation and it will do it anywhere.</blockquote><p>For most projects, this shouldn’t be a problem; however, a large codebase may lose some performance. To avoid this, we can do:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bee38c7b54713b34340ba9dddfaccb57/href">https://medium.com/media/bee38c7b54713b34340ba9dddfaccb57/href</a></iframe><h4>Rendering</h4><p>To force HTML generation directly, use hiccup.core/html function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UgmJ3kQ6ELWcF1MN-W_JUw.png" /></figure><p>That’s it — the gist of Hiccup. Thanks for reading. Take a look at the resources below if you want to delve deeper and maybe my other stuff. If you have any questions, please feel free to send me an e-mail or leave a comment.</p><h3>Resources</h3><ul><li><a href="https://github.com/weavejester/hiccup/wiki">https://github.com/weavejester/hiccup/wiki</a></li><li><a href="http://weavejester.github.io/hiccup/index.html">http://weavejester.github.io/hiccup/index.html</a></li><li><a href="https://github.com/yokolet/hiccup-samples">https://github.com/yokolet/hiccup-samples</a></li><li><a href="https://purelyfunctional.tv/mini-guide/hiccup-tips/">https://purelyfunctional.tv/mini-guide/hiccup-tips/</a></li><li><a href="http://www.rkn.io/2014/03/13/clojure-cookbook-hiccup/">http://www.rkn.io/2014/03/13/clojure-cookbook-hiccup/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6494e477f3a5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/makimo-on-software-development/hiccup-lightning-tutorial-6494e477f3a5">Hiccup Lightning Tutorial</a> was originally published in <a href="https://medium.com/makimo-on-software-development">Makimo On Software Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactive Coordinators Pattern Proof of Concept with RxJS]]></title>
            <link>https://medium.com/makimo-on-software-development/reactive-coordinators-pattern-proof-of-concept-with-rxjs-e9babf566c2a?source=rss----98fc48642ba7---4</link>
            <guid isPermaLink="false">https://medium.com/p/e9babf566c2a</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Marcin Struś]]></dc:creator>
            <pubDate>Tue, 18 Jun 2019 14:08:09 GMT</pubDate>
            <atom:updated>2019-06-18T14:08:09.402Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dNV9OhgwrsDtioChluUgvQ.png" /></figure><p><em>Note: this article assumes that you have a basic understanding of the Reactive Extensions concepts and usage. Also, several references to the iOS application architecture are made along with the story. However, these concepts are not critical for understanding the main ideas of the article.</em></p><p>Developing GUI application architecture is hard. The structures that control the behavior and appearance of our views may quickly get overcomplicated and overengineered. However, there are certain tools that are helpful in keeping the code simple and maintainable. In <a href="https://medium.com/makimo-tech-blog">Makimo</a> we decided to try out mixing several ideas to design clean application architecture. From a combination of Reactive Extensions, MVVM and Coordinator Pattern we created the pattern that, for the purpose of this article, is called Reactive Coordinators. Although the Coordinator Pattern was bred for and by the iOS developers, we will present proof of concept in Node.js. The PoC will be a simple terminal based application that handles user authentication against some API.</p><h3>The Coordinator Pattern</h3><p>The Coordinator Pattern was introduced in 2015 by <a href="http://khanlou.com/2015/10/coordinators-redux/">Soroush Khanlou</a>. It solves the problem of placing the navigation logic within the iOS application. Previously, the code controlling transitions between the views was placed within <a href="https://developer.apple.com/documentation/uikit/uiviewcontroller">UIViewControllers</a> which were also responsible for providing data for the views, handling user input, contacting data sources and so on. This usually led to Massive View Controller antipattern. A lack of separation of concerns is implied in the official Apple developer documentation, but this is a topic for another time. Apart from being overstuffed, the UIViewControllers needed to know about each other to manage the transitions: for instance, the login view needed to know where the user should be after successful login. As a result, tight coupling between views that logically were not as close to each other was plaguing iOS applications.</p><p>Soroush Khanlou suggested extraction of navigation logic into the separate components that would oversee the transitions between views. These components, called coordinators, should be responsible for creating the views, injecting dependencies and presenting them to the user. The coordinator reference must be passed to the managed view to allow backward communication: the view may notify that it was dismissed or completed so the coordinator can show another view (for instance present dashboard after successful login).</p><p>The coordinators themselves are organized into a tree structure. This allows to separate application parts: for example, the authentication flow can be controlled by different coordinator than the product purchase flow in a shopping app. The parent coordinator passes the control to its child and regains it when the child decides that it is done.</p><p>The Coordinator Pattern allows the UIViewControllers to be loosely coupled, thus increasing their testability and maintainability. The programmer can organize the flow of an app with ease and flexibility.</p><h3>Model-View-ViewModel</h3><p>Another way of decluttering the UIViewController was the integration of Model-View-View Model architecture. The MVVM was announced by <a href="https://blogs.msdn.microsoft.com/johngossman/2005/10/08/introduction-to-modelviewviewmodel-pattern-for-building-wpf-apps/">Microsoft </a>in 2005. This pattern separates the view layer from a model with a component called a View Model.</p><p>The main responsibility of the View Model is the preparation of data provided by the Model layer (for example from database or API) so it is ready to be displayed by the View layer. The Views in this architecture should be stripped of any logic as much as possible. All formatting and data validation must be done by the View Model. Furthermore, the View Model is responsible for handling user input and modifying the Model accordingly. For example, if a user submits an order form, the View Model contacts Model layer and commits the purchase. At the same time, View Model notifies the View that some sort of progress bar or activity indicator should be displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*IrFHXhr4zXdCE5KuSE2Shg.png" /><figcaption>Model — View — View Model application architecture.</figcaption></figure><p>Communication between View Model and View is achieved by data bindings. They may be unidirectional (for example displaying product details on the product page) or bidirectional (handling order form during the purchase process). Data bindings should carry display-ready data so that they need no additional processing on the View side.</p><p>This leads the much cleaner architecture with a clear separation of concerns. Also, the testability is greatly improved as the View Models can be tested separately from the Views.</p><h3>Reactive Extensions</h3><p>MVVM plays very nice with the <a href="http://reactivex.io/">Reactive Extensions</a>. In MVVM the reactive streams are usually used to do the data binding between the Views and View Models. The View Model provides observables that are subscribed by View and which stream data that should be displayed. The other way round, the View provides observables that represent user actions, ie. button clicks. After the bindings are done, the View can react to the changing data and View Model can dispatch actions in response to user actions.</p><h3>The complete idea</h3><p>To sum up, our proposed application architecture consists of the following components:</p><ol><li>Model which manages business logic and performs data access.</li><li>View which displays data provided by the View Model and notifies the Coordinator about need for navigation with observables.</li><li>View Model which communicates with the Model and orders it to perform certain operations on the application data in response to user events obtained from View and passes the data that should be displayed in response; all the communication is done via Rx observables.</li><li>Coordinator which navigates between Views and injects dependencies both into Views and Views Models.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*8bxN0uqo371nYrAPh3KuqA.png" /><figcaption>The proposed application architecture.</figcaption></figure><h3>The secret sauce</h3><p>There was one more thing we added to the mixture to create the Reactive Coordinators. Usually, the Coordinators and View Models are modeled as instances of some classes providing required functionalities. Data bindings between View Model and View are modeled as properties of these objects, while the user input is handled via methods.</p><p>However, there is <a href="https://medium.com/grailed-engineering/modeling-your-view-models-as-functions-65b58525717f">no need for them to be objects</a> at all. The Coordinators, View Models and even Views may be modeled as pure functions, accepting several observables as inputs and returning other observables as outputs. The purity of these entities forces them to be stateless. As a result, the programmer can concentrate on data flows that occur within a developed application instead of managing the state.</p><p>In our proof of concept, we decided to ditch the Views, View Models and Coordinator modeled as objects and make them pure functions. As you will see in a moment, we got a demo that has virtually no state management on the programmer side of things.</p><h3>The demo</h3><p>To illustrate the concept of Reactive Coordinators we have created a simple demo application (actually, part of it). The demo is a simple terminal UI application that performs authentication of a user against remote API. The user may be authenticated either by passing credentials (e-mail and password) or by registering a new account. The demo was written in JavaScript for Node.js environment using <a href="https://github.com/chjj/blessed">Blessed.js</a> library, which is pure JS implementation of <a href="https://invisible-island.net/ncurses/">ncurses</a>, enriched with several widgets that made the prototyping fast enough. Although Blessed seems to be unmaintained and we do not recommend using it in production code, it was good enough for the proof of concept. As a reactive streams library, we have used RxJS in the current stable version.</p><h4>Entrypoint</h4><p>After running the main entry point, the first coordinator should be started. As was said previously, the coordinators are organized in a tree. The root of the tree is also a coordinator which is usually called an App Coordinator. In our proof of concept, it is modeled as a pure function appCoordinator:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8472e960002d599fbae4c2473c45e03/href">https://medium.com/media/e8472e960002d599fbae4c2473c45e03/href</a></iframe><p>The screen is a Blessed.js object that is used to render widgets in the terminal. It is used to hold the hierarchy of the displayed views. The first thing to notice with our concept: the dependency injection is implemented with passing proper function arguments. Since the navigation flow is controlled by the programmer, there is no need to use any external libraries that manage the dependency injection logic.</p><p>The dispose is an observable that emits value when the appCoordinator is finished (we’ll get to this in a moment). The connector is a group of functions that implement API communication. In this case, these functions are register and login:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cdd96a4e7a541b35ec272f6c21832d4/href">https://medium.com/media/2cdd96a4e7a541b35ec272f6c21832d4/href</a></iframe><h4>Application coordinator</h4><p>The application coordinator has a simple task. It should invoke its child, the authCoordinator which is responsible for handling authentication flow (either registration or login) and wait for its result:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7fdd8424d00922a2b23ac85248f1ae7/href">https://medium.com/media/d7fdd8424d00922a2b23ac85248f1ae7/href</a></iframe><h4>Auth coordinator</h4><p>The authentication coordinator is a bit more interesting. Initially, it presents the screen with two buttons which allow a user to display either login or registration form. The user may choose whichever option to perform authentication. The authentication coordinator should notify its parent when the API returned valid token as a result of either operation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50f39e327bad1d5abd57344d3ef5accd/href">https://medium.com/media/50f39e327bad1d5abd57344d3ef5accd/href</a></iframe><p>The showLogin and showRegister are functions where our coordinators start interacting with a view:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0596739fe1f1742d123a2da657e29529/href">https://medium.com/media/0596739fe1f1742d123a2da657e29529/href</a></iframe><p>Both showLogin and showRegister call functions that set up corresponding views (loginView and registerView). These functions return observables that are used as a notification channel grouped into outputs object. Also, view, a Blessed.js object, is returned. It is the coordinator job to push it to the screen.</p><p>We have introduced to the coordinator another concept: the dispose bags. It may sound familiar to those who program in RxSwift: the dispose bag holds references to the subscriptions made by the view and unsubscribes all of them when it is thrown away. Unfortunately, the RxJS does not implement it. However, there is a trick: subscriptions can be added to other subscription. When the parent subscription is unsubscribed, all children as unsubscribed as well. In our implementation, the dispose bag is attached to the view pushed to the screen and is injected into both View Model and View. When the view is removed from the screen, the dispose bag is unsubscribed. This allows us to keep track of what subscriptions are associated with what view.</p><p>There is also one more thing to be noticed: the View Model associated with instantiated View is injected into it. This allows injecting dependencies into the View Model without involving the View: the View does not need to know anything about what View Model is going to use internally.</p><h4>The View and View Model</h4><p>Let’s see what is going on inside the loginView (the registerView is analogous, so it does not need to be covered):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e6e631504fcdf30561d102c1392982f/href">https://medium.com/media/6e6e631504fcdf30561d102c1392982f/href</a></iframe><p>The loginView initializes the view and its controls. Then it passes observables created from the inputs to the View Model and collects outputs. Finally, the subscription to error message is created and the outputs relevant to the coordinator (in this case the observable that emits JWT token returned by the API). Also, this View will ask the coordinator to be dismissed when the user presses Escape key.</p><p>The View Model for login view is also simple:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b0ad8a746ab9ddc2d59b06ab0d6f146/href">https://medium.com/media/7b0ad8a746ab9ddc2d59b06ab0d6f146/href</a></iframe><p>The login view model simply takes inputs provided by the view as well as observable that emits value when the user hits the submit button. Its responsibility is to send the request to the API to verify user credentials. This is achieved with two utility functions: mapForm and submitForm:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f14cd9445bfcb03ceffe849b9894012b/href">https://medium.com/media/f14cd9445bfcb03ceffe849b9894012b/href</a></iframe><p>The most important property of loginView and loginViewModel it the fact that neither of them knows nothing about each other. The only shared knowledge is the inputs and the outputs that each of them needs to do their job. This results in the extremely low coupling between the components. As a result, they may be developed in complete isolation. The testability is also greatly improved: they are just pure functions that accept arguments and return results. Creating unit tests in such a case is more than pleasant.</p><h3>Conclusions</h3><p>In our proof of concept the components turned out to be less coupled than in the original Coordinator Pattern: the Views managed by the Coordinator don’t need to have a reference to the managing Coordinator (as in the original approach). As a result, the components only know what they need for completing their tasks. This decoupling results in greater testability and isolation of application components.</p><p>It is worth mentioning, that the presented solution completely removes state that the programmer should take care of. The application is modeled as data flows instead. This significantly reduces the mental load of the programmer when it comes to reason about the system. Also, this is another reason that the tests are much easier to design.</p><h4>Possible improvements</h4><p>Presented code is just rough-and-dirty proof of concept and it is far from being a production code. Several improvements could be made:</p><ul><li>Some sort of library for immutable data (like <a href="https://github.com/immutable-js/immutable-js">Immutable.js</a>) could be used to increase security and make the transformations withing reactive streams easier.</li><li>Usage of the library that embraces functional concepts (for instance: <a href="https://github.com/ramda/ramda">Ramda</a>) could reduce boilerplate and increase the readability of introduced dependency injection mechanism.</li></ul><p>Both improvements could be made “for free” using other technology. One that comes to our minds is Clojure(Script) with core.async for reactivity. It’s something we have been wrapping our heads around lately and we will for sure share our impressions as soon as we try it out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9babf566c2a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/makimo-on-software-development/reactive-coordinators-pattern-proof-of-concept-with-rxjs-e9babf566c2a">Reactive Coordinators Pattern Proof of Concept with RxJS</a> was originally published in <a href="https://medium.com/makimo-on-software-development">Makimo On Software Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[On Lisp in 15 minutes]]></title>
            <link>https://medium.com/makimo-on-software-development/on-lisp-in-15-minutes-3286c179584f?source=rss----98fc48642ba7---4</link>
            <guid isPermaLink="false">https://medium.com/p/3286c179584f</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[lisp]]></category>
            <category><![CDATA[clojure]]></category>
            <dc:creator><![CDATA[Iwo Herka]]></dc:creator>
            <pubDate>Fri, 24 May 2019 12:03:23 GMT</pubDate>
            <atom:updated>2019-07-06T11:19:19.263Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TmTwv0MN_IQMgdGj83N20w.jpeg" /></figure><blockquote>LISP is simple and difficult, elegant and ad hoc; it is a beautiful blend of foresight and fortuity.¹</blockquote><p>Whether you agree with this statement or not, Lisp’s historical importance is indisputable. Even though a beautiful language in its own right, Lisp turned to be one of the most influential models<em> </em>of computer programming. It also gave birth to many widespread concepts in the industry today and, as mainstream is steadily shifting from von Neumann style to λ-calculus, we can suspect many to be adopted in the future. In effect, Lisp is of interest to both a historian and a futurist. Paul Graham suggested that what John McCarthy did for programming was something like what Euclid did for geometry². What is so important that McCarthy discovered? To answer this question we have to put aside decades’ worth of Internet mythos and take a look at Lisp’s humble beginnings — <em>Recursive Functions of Symbolic Expressions and Their Computation by Machine, Part I</em>³ by John McCarthy. In this article, I will follow his steps in order to explain how Lisp was constructed.</p><p><em>I’m writing this article to practice my understanding and appreciation of McCarthy’s work. The goal of this article is to explain how Lisp came to be and discuss properties that make it special. Hopefully, someone will find it useful. I highly recommend reading the original paper, and Paul Graham’s take on it, after this short introduction (see References).</em></p><h3>1. Preliminaries</h3><p>Lisp is constructed from the bottom. It is only appropriate that we start by laying out basic ideas and notations concerning functions which we will use later on. Most of the concepts presented here are well-known, so feel free to skip this section.</p><h4>1.1. Partial functions</h4><p><a href="https://en.wikipedia.org/wiki/Partial_function"><em>Partial functions</em></a> (not to be confused with the partial application!) are functions that are defined only for parts of their domains. The <a href="https://en.wikipedia.org/wiki/Domain_of_a_function"><em>domain of a function</em></a><em> </em>is a collection of all possible arguments to a function. Most of the functions in computer programs are partial (at least in imperative languages). Consider the following example (in Python):</p><pre>def one_nth(n):<br>    return 1 / n</pre><p>or, a bit more involved:</p><pre><strong>def </strong>query_purchases(client: BillingClient) -&gt; List[Purchase]:<br> <strong>   if </strong>client.is_initialized:<br>        return client.query_purchases()<br>    <strong>else:</strong><br>        raise Exception(&#39;Billing client is not set up&#39;)</pre><p>The behavior of these functions (in a mathematical sense) is undefined for certain inputs, as passing zero to one_nth or uninitialized client to query_purchases will result in an exception. Another possibility is that functions may not terminate, e.g. when caught in infinite recursion. It derives from the fact that the type systems are often too weak to constrain the type as much as the programmer would like or the penalty of assigning more precise type is too high. In mathematics, we don’t have this problem. In case of one_nth, we could simply say that the domain of the function is ℝ \ {0}.</p><blockquote>One example of a more “expressive type” system is Idris’, which supports dependent types. Although dependent types are a story for another time, in short, it simply means that types themselves are dynamic and first-class, in the sense that they possess properties related to values they take. For example, a function taking argument N may return the type of list which is no longer than N.</blockquote><p>In general, any function that can result in an error, or does not terminate for some of its inputs, is considered partial.</p><blockquote>In some languages, such as Haskell, a computation which never completes successfully is referred to as “bottom” and denoted with “⊥”. Therefore, when the evaluation of a partial function results in a partial behavior (such as a crash), its value is ⊥.</blockquote><blockquote>In Racket, Lisp dialect, the programmer can explicitly mark a function as partial.</blockquote><blockquote>Sometimes, when it is desirable to suppress errors and exceptions, a special value might be returned acting as a bottom, such as IEEE floating point’s <a href="https://en.wikipedia.org/wiki/NaN">not-a-number</a> (<em>NaN</em>).</blockquote><p>Analogically, when a function is <em>total</em>, we can say that it produces a valid result for all possible inputs. For example, the <a href="https://docs.racket-lang.org/hackett/reference-datatypes.html#%28def._%28%28lib._hackett%2Fmain..rkt%29._not%29%29">f</a>unction not is obviously defined for both True and False, which are the only possible values of the bool type. Total functions allow a programmer to reason about programs using the types alone; a function with the type <em>A</em>→<em> B</em> implies that it is always possible to get a <em>B</em> when you have an <em>A</em>.</p><h4>1.2. Predicates</h4><p>A <a href="https://en.wikipedia.org/wiki/Predicate_(mathematical_logic)">predicate</a> is a function whose codomain (set of all possible outputs) consists only of truth values (i.e., truth or falsehood). A common convention is to denote truth with t and falsehood with f (in the original paper McCarthy used uppercase letters). Simply put, a predicate must return a Boolean.</p><h4>1.3. Pure functions</h4><p>One of the most important advantages of purely functional approach over imperative one (and by extension OOP) is <em>referential transparency</em>, which guarantees that for a specific set of arguments a function (or generally, an expression) will always return the same result (it is entirely predictable). In other words, an evaluation of an expression can have no effect other than to compute its value. As a result, one can freely replace expressions by their values. Functions with this property are called <em>pure</em>. Almost all functions in imperative environments are impure.</p><h4>1.4. Conditional Expressions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*dUJOTjCsp6QI7Q8FuX_Z1g.png" /></figure><p>The function above is a well-known <em>absolute value</em>. Because its value depends on the condition (whether <em>x</em> is greater-or-equal to zero), we can say that it is <em>conditional</em> in its behavior. However, this notation is not suited for expressing symbolically the dependence of quantities on truth values — it has to rely on English words.</p><p>A better notation for representing conditional expressions was proposed by McCarthy (now referred to as <a href="https://en.wikipedia.org/wiki/McCarthy_Formalism">McCarthy formalism</a>):</p><pre>(p₁ → e₁, … , pₙ → eₙ)</pre><p>Here, the <em>p</em>’s are propositional expressions and the <em>e</em>’s are expressions of any kind. It may be read as:</p><p><em>If p₁ then e₁ otherwise if p₂ then e₂, … , otherwise, if pₙ then eₙ.</em></p><p>Notice how we are assuming here the evaluation order — we consider <em>pᵢ</em> from left to right. With this notation under our belt, we can express the absolute value function simply as:</p><pre>(x ≥ 0 → x, x &lt; 0 → -x)</pre><p>More importantly, however, this notation is sufficient to express <strong>any</strong> <em>if-then</em> statement. For example:</p><pre>if n % 3 == 0 and n % 5 == 0:<br>    return &#39;FizzBuzz&#39;<br>elif n % 3 == 0:<br>    return &#39;Fizz&#39;<br>elif n % 5 == 0:<br>    return &#39;Buzz&#39;<br>else:<br>    return n</pre><p>…can be expressed as:</p><pre>(3 ∣ n ∧ 5 ∣ n → &#39;Fizzbuzz&#39;,<br> 3 ∣ n → &#39;Fizz&#39;,<br> 5 ∣ n → &#39;Buzz&#39;,<br> t → n)</pre><blockquote><em>m | n</em> means that <em>n</em> is divisible by <em>m</em>, or <em>m</em> divides <em>n</em>.<em>∧</em> is standard logical conjunction, or AND in Boolean algebra.</blockquote><blockquote>Notice how by exploiting the left-to-right evaluation order we can encode the <em>else</em> clause using the <em>t</em> value.</blockquote><p>Conditionals were introduced by Lisp. In effect, <em>if</em> statements, as we know them today, are thanks to McCarthy. As of 1958, Fortran only had a conditional <em>goto </em>which was based on the branch instruction in the underlying hardware. McCarthy also got conditionals into Algol 60, whence they spread to most other languages⁸.</p><h4>1.5. Recursive functions and label</h4><p>Thanks to conditional expressions given above, we can now define functions recursively. For example, we can define <a href="https://en.wikipedia.org/wiki/Factorial">factorial</a> as:</p><pre>n! = (n = 0 → 1, t → n · (n − 1)!)</pre><p>Note, however, that we are making here one very important assumption — the body of the function can reference the function itself by its name (or symbol — ! in this case).</p><blockquote>In most actual languages this is not a problem, but remember — we do not have any language yet!</blockquote><p>In general, we can solve this problem with something called <a href="https://en.wikipedia.org/wiki/Fixed-point_combinator#Fixed_point_combinators_in_lambda_calculus"><em>Y combinator</em></a>, but that’s a topic for another time. As McCarthy most likely was not aware of Y combinator at the time of writing his paper, he introduced his notation instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*qd4-nDagTCigcG6avrrVMg.png" /><figcaption><strong>Fig 1.</strong> McCarthy in his AI laboratory at Stanford</figcaption></figure><p>label(a, e) denotes the expression e, with the special property that all occurrences of a<em> </em>within e are to be interpreted as referring to the expression e itself. Therefore, by combining <em>label</em> with conditional expressions, we can define <a href="https://en.wikipedia.org/wiki/Greatest_common_divisor#Using_Euclid&#39;s_algorithm">Euclid’s algorithm</a> for calculating the greatest common divisor as follows:</p><pre>label(gcd, (m &gt; n → gcd(n, m),<br>            m | n → m,<br>            t → gcd(n % m, m)))</pre><p>It is important to note that although recursion existed as a mathematical concept before Lisp, Lisp was the first programming language to support it.</p><h3>2. S-expressions</h3><p>First, we define <em>a</em> <em>symbolic expression (s-expression, </em>or just <em>expression</em> for<em> </em>short<em>)</em>. An s-expression is either:</p><ul><li><em>an atom</em>, which is a sequence of characters, e.g. spam, ham, eggs or f*&amp;o$o. An atom cannot start with (, which is reserved for lists.</li><li><em>a list </em>of zero or more s-expressions which are separated by whitespace and enclosed by parentheses. For example: (abc) , (), (a (bc)).</li></ul><p>In simplified <a href="https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form">extended Backus-Naur form</a> (commonly used for describing the syntax of a language), s-expressions can be represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pBmVpeV2l9ZID5eM63rkZw.png" /><figcaption><strong>Fig. 2</strong> Simplified <a href="https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form">EBNF</a> for s-expressions</figcaption></figure><p>— which is the exact restatement of the definition given above (except that atoms are assumed to be alphanumeric).</p><p>The above definition is recursive, as we are referring to s-expressions while defining lists of s-expressions. Some examples of valid s-expressions include:</p><pre>()<br>foo<br>(bar)<br>(foo bar)<br>((spam) (ham ()) eggs ())</pre><p>— but also:</p><pre>(+ 1 2 3 5 8 13)<br>(&gt; 24 512 12)<br>(and true false true)</pre><h3>3. Abstract machine</h3><p>“The most practical way to think about the meaning of a program is what it does — when we run the program, what do we expect to happen? How do different constructs in the programming language behave at run time, and what effect do they have when they’re plugged together to make larger programs? This is the basis of operational semantics, a way of capturing the meaning of a programming language by defining rules for how its programs execute on some kind of device. This device is often an abstract machine: an imaginary, idealized computer that is designed for the specific purpose of explaining how the language’s programs will execute. Different kinds of a programming language will usually require different designs of an abstract machine in order to neatly capture their runtime behavior.”⁷ In order to construct Lisp, we first construct an imaginary machine on which it will operate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*rfd8XQqc8ze-iMvgvuUN9w.jpeg" /><figcaption><strong>Fig. 3</strong> <a href="https://zeptobars.com/en/read/ST-UA741-opamp-operational-amplifier">ST µA741 op-amp</a>, or: imaginary Lisp machine</figcaption></figure><h4>3.1. Elementary functions</h4><p>We start by defining seven (<em>The Magnificent Seven, </em>in fact) elementary functions on s-expressions. We call them elementary because we assume they exist on the abstract machine (just like we assume axioms to be true in some mathematical system). A function on s-expression receives an s-expression and returns a new one. By convention, we will refer to such functions as <em>operators</em>.</p><blockquote>To keep our notation simple, we <strong>represent</strong> operators using atoms and lists — if an s-expression is a list, the first element is an operator, and remaining ones are <em>arguments</em>. This means that functions on s-expressions are encoded using s-expressions themselves. For example, the <em>car</em> operator expects one argument, and so its invocation will take the form:</blockquote><pre>(car x)</pre><p>Atom “car&quot; on its own refers to the function itself. If car expected an argument which is a function (it doesn’t), we could write (car car).</p><h4>atom</h4><p>atom is a very simple operator; it just returns t if the argument passed is an atom, and otherwise.</p><pre>&gt; (atom f)<br>t<br>&gt; (atom foo)<br>t<br>&gt; (atom atom)<br>t</pre><h4>quote</h4><p>quote is even simpler, it returns whatever was passed into it.</p><pre>&gt; (quote x)<br>x</pre><pre>&gt; (quote (atom x))<br>(atom x)</pre><pre>&gt; (quote (1 2 3 4 5))<br>(1 2 3 4 5)</pre><p>It is crucial to understand how quote behaves and why is useful. The second example — (quote (atom x)) —will reduce to the list containing atom and x. (atom x) is not “evaluated” further (at this point we do not know what evaluation even is, but let us ignore that for a second). In essence, quote is used to stop the evaluation — normally in(1 2 3), 1 would be assumed to be an operator but we want to treat the list as a regular list. This is why we would use quote. It is usually abbreviated with &#39;, which gives us:</p><pre>&gt; &#39;(1 2 3)<br>(1 2 3)</pre><p>Now that we have quote , we can go back to atom for one more example:</p><pre>&gt; (atom &#39;(foo bar baz))<br>f</pre><p>If the code would eventually be evaluated by some kind of program capable of doing that, quote would prevent evaluation of any s-expression given as its argument, which is very important when passing data around.</p><h4>eq</h4><p>eq returns t if the values of its arguments are the same atom and f otherwise.</p><blockquote>Some languages, such as Scheme, use <em>eq?</em>. Clojure uses <em>=</em>.</blockquote><h4>car</h4><p>car expects a list as an argument and returns its first element. It&#39;s name, similar to cdr, is a historical legacy.</p><pre>&gt; (car &#39;(1 2 3 4))<br>1</pre><blockquote>Certain languages, such as Clojure, rename <em>car</em> with something more intuitive, e.g. <em>first</em>. The “car” and “cdr” names are derived from the machine architecture that Lisp was designed for and nowadays languages use more familiar names.</blockquote><h4>cdr</h4><p>cdr expects a list as an argument and returns its back without the first element. For example:</p><pre>&gt; (cdr &#39;(1 2 3 4))<br>(2 3 4)</pre><blockquote>In Clojure, <em>cdr</em> behavior is provided via<em>rest</em>.</blockquote><h4>cons</h4><p>cons (<em>construct</em>) takes two arguments, second of which must be a list, and prepends the list with the first argument:</p><pre>&gt; (cons 1 &#39;(2 3))<br>(1 2 3)</pre><blockquote>Why would we prepend to lists instead of appending them is a topic on its own. In short, lists constructed as the head and rest are simpler to manipulate recursively, which is a huge benefit for a language such as Lisp.</blockquote><h4>cond</h4><p>We will now translate conditional expressions into s-expressions using cond. cond has the following form:</p><pre>(cond (p₁ e₁) ... (pₙ eₙ))</pre><p>The value is evaluated as follows. We evaluate p expressions from left to right. If any predicate evaluates to t, the value of the cond expression is taken to be the value of the corresponding expression e. For example:</p><pre>&gt; (cond (t 1) (f 2))<br>1</pre><p>Moreover, because we evaluate from left to right:</p><pre>&gt; (cond (t 1) (t 2))<br>1</pre><h4>3.2. Denoting non-elementary functions</h4><p>With basic functionality in place, we define a general scheme for defining new functions on the abstract machine. A function is expressed as</p><pre>(lambda (p₁ … pₙ) e)</pre><p>where <em>p₁ -pₙ</em> are called <em>parameters</em> and <em>e </em>is an <em>expression</em>. If you ever tinkered with lambda calculus (or with lambdas/anonymous functions in pretty much any modern programming language), you will recognize this notation.</p><p>An expression whose first element is a lambda, i.e., is of the form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*GPsMQKDkxsH9NwqowLTTHw.gif" /></figure><p>— is called a function call and its value is computed as follows. Each expression <em>aᵢ</em> is evaluated. Then <em>e</em> is evaluated. During the evaluation of <em>e</em>, the value of any occurrence of one of the <em>pᵢ</em> is the value of the corresponding <em>aᵢ</em> in the most recent function call.</p><p>Do you remember <em>label </em>notation<em>?</em> We can now translate it to s-expression form and use it on our abstract machine to obtain a general method for defining functions. The label s-expression will have the following form:</p><pre>(label <em>name lambda</em>)</pre><p>— where <em>name </em>is an atom representing the name of the function and <em>lambda </em>is the function body, also called to <em>form</em>.</p><p>Using label and the <em>Magnificent Seven</em> our expressive power is limitless.</p><p>For example, we can define the Boolean operator <strong>NOT</strong>:</p><pre>(label not (lambda (x)<br>    (cond (x f) (t t))))</pre><pre>&gt; (not t)<br>f</pre><pre>&gt; (not f)<br>t</pre><p>As you can see, <strong>NOT </strong>expects one argument — <em>x</em>. In the body of the function, we perform a conditional check of <em>x</em>. If the value is equal to t, we return f and otherwise t (t in the last positional of the <em>cond</em> acts as the <em>else</em> clause in modern languages, since the condition is always true).</p><p>Next, we can define a bit more involved Boolean<strong> AND</strong>:</p><pre>(label and (lambda (x y)<br>    (cond (x (cond (y t) (t f)))<br>          (t f))))</pre><pre>&gt; (and t f)<br>f</pre><pre>&gt; (and t t)<br>t</pre><p>This body can be summarized as: If <em>x</em> is true, check if <em>y</em> is true and if so, return t. If <em>y</em> is not true, or <em>x</em> is not true, return f (we have two <em>else</em> clauses).</p><p>We can write functions to manipulate lists, Boolean expressions, pair elements, rewrite expressions, and so on. For example:</p><ul><li>(not x) returns t if its argument returns f and t otherwise.</li><li>(pair x y) takes two lists of the same length and returns a third one containing two-element lists of corresponding elements in argument lits. Nowadays we would more likely call this function zip.</li><li>(append x y) takes two lists and concatenates them.</li><li>(assoc x y) takes an atom x and a y of the form return by pair and returns a second-element from a pair in y whose first element is x. This function emulates a lookup into a dictionary (alternatively called a hash table or associative array).</li></ul><blockquote>It is important to note that in Lisp, functions are first class objects — they’re data, just like numbers and strings. Therefore, functions can be stored in variables, passed around as arguments, and so on. The idea of a first-class function was pioneered by Lisp.</blockquote><h4>3.3. Evaluation</h4><p>More importantly, however, we can write a function that takes arbitrary Lisp expression and returns its value:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e32cbaa4fa84da8db305b5db750c85e1/href">https://medium.com/media/e32cbaa4fa84da8db305b5db750c85e1/href</a></iframe><p>That is a bit of mouthful. If you want a step by step description, which is beyond the scope of this article, I recommend reading <em>Recursive Functions…</em> by McCarthy³ and Paul Graham’s <em>The Roots of Lisp</em>², which take a thorough look at eval‘s inner-workings.</p><p>The important thing is this: eval <strong>is a Lisp interpreter</strong>, and thus, implements the language. Any valid Lisp code can be passed to it for evaluation and we don’t need any other infrastructure. With only seven functions and a bit of notation, we were able to implement the whole language and allow it to define new functions. That’s neat and very elegant, but so what? Now that we understand how Lisp operates, let’s step back and consider what it means.</p><blockquote>If you’re curious how Lisp can be implemented in a few hundred lines of code, check out my toy Lisp implementation: <a href="http://github.com/iwoherka/kite">Kite</a>.</blockquote><h3>4. Chemical X: Homoiconicity</h3><p>In Lisp, as we saw, both code and data are represented in the same form: as s-expressions (forming trees) which are available for unrestricted mutation and execution. This means that <strong>the Lisp code is <em>first-class</em></strong>. It can be explicitly constructed from scratch, passed around, modified and executed. In other words, in Lisp <em>everything is data</em>. A language in which the internal «representation matches the external representation is called <em>homoiconic </em>(from the Greek words <em>homo</em> meaning “the same” and <em>icon</em> meaning “representation”). Other examples of a language with this property include Prolog (logic programming) and Julia (numerical analysis and computational science). One of the immediate consequences of homoiconicity is that by using just a few functions: quote, atom, eq, car, cdr, cons, and cond, we can define eval, that fully implements the language, and with label and eval we can define any additional function we need. In fact, it is a famous fact that the core of the Lisp can be written in about 20–30 lines of Lisp. In (an unfair) comparison, the average person who writes a C compiler or interpreter requires about 20,000 lines of C to do so and must be moderately expert about compilers or interpreters (of course, we rely on <em>meta-circularity</em> in doing so, but that’s a topic for another post). At this point, you may be asking yourself — what’s the big deal?</p><p>The big deal, as it turns out, that when the representation of the program (code) is the same as the representation for that data, you can manipulate code like you would manipulate data. This allows, for example, for syntactic extensibility, which is the ability to extend (or completely) change the syntax of the language. For example, in a normal language, if you wished that you had the <em>for-each </em>construct, you would have to wait until creators of the language add it in the next version. In Lisp, you can write a macro in a matter of minutes. In many Lisp languages, program transformation is an explicit part of the evaluation strategy of the language.</p><p>Moreover, in Lisp, programs composed of expressions. Lisp programs are trees of expressions, each of which returns a value. At the time, this was a revolutionary idea, in contrast to languages such as Fortran which distinguish between expressions and statements. This was largely dictated by the limitations of the hardware available in the late 1950s.</p><p>Finally, what McCarthy discovered is not just a programming language but a very elegant <em>model of computation</em>, just a notch above lambda calculus. We can say that Lisp was discovered, and not invented, because McCarthy built it from axioms so fundamental that it would be very hard to make an argument for the otherwise.</p><p>Core Lisp corresponds to <em>an untyped, call-by-value lambda calculus extended with constants. </em>As it turned out, lambda calculus* corresponds to natural deduction in logic. Specifically, by Curry-Howard isomorphism, types in a program are propositions, programs are proofs and evaluation of programs is the simplification of proofs. This discovery is phenomenal. Among others, it means that we can reason about programs using logic and that we get theorems in logic for free in programming (and vice versa).</p><p>The big difference between Lips and lambda calculus is that lambda calculus doesn’t contain any non-functional data. In lambda calculus, everything is a function, even a number (if you’re curious how this is achieved see <a href="https://en.wikipedia.org/wiki/Church_encoding">Church encodings</a> or <a href="https://en.wikipedia.org/wiki/Mogensen%E2%80%93Scott_encoding">Mogensen-Scott encodings</a>). Lisp, on the other hand, operates on atoms and numbers (hence, <em>constants</em>). This is most likely what makes Lisp readable to mortal humans — a property that lambda calculus lacks.</p><p>The adherence to mathematically sound principles of computation allows Lisp to reap the benefits in the form of simple semantics, clarity, consistency, and other nice things such as referential transparency (original Lisp formulation is completely value-based). In contrast, almost all imperative languages are “just” tools (sometimes very good tools nonetheless) with undefined formal semantics, which makes reasoning about them rigorously very hard or almost impossible.</p><p>Thank you for reading. Please check out the references and maybe my other <a href="http://iwoherka.eu/">stuff</a>. If you have any questions, please feel free to send me an e-mail at <em>hi@iwoherka.eu</em> or leave a comment.</p><p>*Specifically, typed lambda calculus. For more details, I highly recommend great talk by Philip Wadler, co-creator of Haskell —<a href="https://youtu.be/IOiZatlZtGU"> Propositions as Types</a>.</p><h4>References</h4><ol><li><a href="https://archive.org/details/byte-magazine-1979-08"><em>BYTE Magazine, August 1979</em></a></li><li><a href="http://www.paulgraham.com/rootsoflisp.html"><em>The Roots of Lisp</em></a></li><li><a href="http://Recursive functions of symbolic expressions and their computation by machine, Part I"><em>Recursive functions of symbolic expressions and their computation by machine, Part I</em></a></li><li><a href="https://twobithistory.org/2018/10/14/lisp.html"><em>How Lisp Became God’s Own Programming Language</em></a></li><li><a href="http://c2.com/cgi/fullSearch?search=HomoiconicLanguages"><em>Homoiconic Languages</em></a></li><li><a href="http://www.paulgraham.com/onlisp.html"><em>On Lisp</em></a></li><li><a href="https://computationbook.com/"><em>Understanding Computation</em></a></li><li><a href="http://www.paulgraham.com/diff.html"><em>What Made Lisp Different</em></a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3286c179584f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/makimo-on-software-development/on-lisp-in-15-minutes-3286c179584f">On Lisp in 15 minutes</a> was originally published in <a href="https://medium.com/makimo-on-software-development">Makimo On Software Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with pdb in Python]]></title>
            <link>https://medium.com/makimo-on-software-development/https-medium-com-iwoherka-working-with-pdb-in-python-8d4f3b42f3f4?source=rss----98fc48642ba7---4</link>
            <guid isPermaLink="false">https://medium.com/p/8d4f3b42f3f4</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Iwo Herka]]></dc:creator>
            <pubDate>Fri, 26 Apr 2019 09:53:13 GMT</pubDate>
            <atom:updated>2019-06-18T13:45:45.457Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Yep, this is another introductory-level article about </em><em>pdb— sue me! The goal is to teach the essentials (and to give a few helpful tips) to those who don’t feel like reading the docs (or get heebie-jeebies when thinking about the console). It is intended for Python 3.</em></blockquote><blockquote>You can watch recorded demonstrations for selected commands on asciinema (links are in the text).</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jWqi_GCi8IXsC-CzoHFwhw.png" /></figure><h3>Why bother?</h3><blockquote><em>Skip to </em>Getting started<em> if you get bored easily</em>.</blockquote><p>As with every console tool, <a href="https://docs.python.org/3.8/library/pdb.html">pdb</a> may seem a bit intimidating. It doesn’t have a nice GUI to hold your hand, and it can feel very cryptic at times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*s52w1-MNaxdaD1nrth5G-A.png" /><figcaption>What’s this all about?</figcaption></figure><p>However, you probably shouldn’t use <em>print</em> to debug your programs, and if you do, it won’t hurt to know what to do when good ol’ <em>print</em> doesn’t cut it. So, unless you can spare a few bucks on a fancy IDE (like PyCharm) there is no avoiding it — you’re going to need pdb sooner or later. However, that’s not necessarily a bad thing; knowledge of the “lightweight” solution can turn out to be very handy. First of all, pdb is textual, and in the long run, typing is a lot faster than clicking. Secondly, it’s optimized for speed — minimal, textual interface doesn’t get in your way. This makes for a slightly steep learning curve, but with a bit of practice, you will start saving on those precious keystrokes in no time. Finally, pdb is a standard module, which means that — regardless of a Python distribution — it is <em>always</em> available (it’s also free and open source, so no vendor locking — yay!). You just need to import it:</p><pre>import pdb</pre><p>In CPython, reference Python implementation, the source code for standard modules resides in the <a href="https://github.com/python/cpython/tree/master/Lib">Lib</a> catalog.<em> </em>Therefore, the pdb’s source code can be found in <a href="https://github.com/python/cpython/blob/master/Lib/pdb.py">Lib/pdb.py</a>. If you have an evening to spare, I recommend taking a look at the source code. There is no better way to understand software than by reading its code. It’s very short too — last time I checked the main file was around 1700 lines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*acgYVKmjRKeAabB_w0tMUQ.jpeg" /><figcaption><a href="https://github.com/python/cpython/blob/master/Lib/pdb.py">Lib/pdb.py</a></figcaption></figure><h3>A bit of jargon</h3><p>pdb is a debugger, which means that it allows you to “spy” on a program while it executes — by inspecting or modifying its runtime — or to see what the program did when it crashed. The latter technique is called <em>post-mortem debugging</em>.</p><p>pdb offers four basic features to help to find bugs:</p><ul><li>Execute the program step by step, under the direct control and supervision of the programmer (which is called <em>single-stepping</em> or <em>program animation</em>).</li><li>Make the program stop on specified lines (so-called <em>breakpoints</em>). pdb also supports <em>conditional breaking</em>, i.e., breakpoints with corresponding Boolean expressions which determine whether debugger should stop upon reaching the breakpoint.</li><li>Examine why or what had happened, when the program had stopped (via symbol resolver or expression interpreter).</li><li>Change the runtime of the program, by modifying the variables, to experiment with the effects it has on the program behavior.</li></ul><p>The program might be executing on the same machine as pdb, on another machine (e.g., with <a href="https://pypi.org/project/remote-pdb/">remote-pdb</a>), might be called by the programmer, or third-party (e.g., when debugging with <a href="https://pytest.org/">pytest</a>).</p><p>*There is also this thing called <em>reverse debugging</em>, but we will talk about it later.</p><h3>Getting started</h3><p>With the introduction out of the way, it’s time to get started with pdb. There are a couple of options to run it.</p><blockquote>Here is the <a href="https://docs.python.org/3.8/library/pdb.html#debugger-commands">documentation</a> for the commands. It’s good to keep it at hand, as we go through the tutorial.</blockquote><h4>Starting from the script</h4><p>Firstly, because the debugger is included in Python’s standard library, we can import it the same way we would any library. Then, we can call <a href="https://docs.python.org/3.8/library/pdb.html#pdb.set_trace">pdb.set_trace()</a> to hard-code a breakpoint (place in which program should halt the execution and yield the control to the programmer). The typical way to do it is:</p><pre>import pdb; pdb.set_trace()</pre><p>However, it implies editing the source code itself. This is invasive and may be considered awkward, but for most of the time, it’s good enough. I highly recommend adding a shortcut to your text-editor for inserting the setup line.</p><p><a href="https://asciinema.org/a/228096">Starting pdb via set_trace</a></p><blockquote><strong><em>New in version 3.7: </em></strong><em>You can use built-in </em><a href="https://docs.python.org/3.8/library/functions.html#breakpoint"><em>breakpoint</em></a><em>() instead of </em><em>import pdb; pdb.set_trace().</em></blockquote><h4>Starting from pdb</h4><p>Secondly, we can reverse the flow of control and run pdb before a single line of code is executed. When invoking Python interpreter with the <em>module</em> option (of the form -m &lt;module-name&gt;), the specified module (given it is located on the Python module path) is executed as a script. By calling python -m pdb &lt;script&gt;, then, we call pdb as a script to debug other scripts. This will result in breaking on the first line in the file:</p><pre>$ python3 -m pdb script.py<br>&gt; /home/siegmeyer/script.py(1)&lt;module&gt;()<br>-&gt; x = 1 # First line in the file.<br>(Pdb)</pre><p>Here &lt;script.py&gt;(1)&lt;module&gt;() means that we are at the first line in the file script.py and no code has been executed yet. If you’re executing from a string, the first part will read &lt;string&gt; (e.g., when starting via <a href="https://docs.python.org/3.8/library/pdb.html#pdb.run">pdb.run</a>).</p><p><a href="https://asciinema.org/a/228099">Starting pdb as a script</a></p><p>Oh, I almost forgot — to exit the debugger type <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-quit">quit</a> or exit. If you’ve started with set_trace , quit/exit will raise bdb.BdbQuit exception, and crash the program (it will <em>not</em> be resumed).</p><blockquote>Side-note: <em>pdb offers three functions (provided by the library, not the prompt) — </em><a href="https://docs.python.org/3.8/library/pdb.html#pdb.run"><em>run</em></a><em>, </em><a href="https://docs.python.org/3.8/library/pdb.html#pdb.runeval"><em>runeval</em></a><em> and </em><a href="https://docs.python.org/3.8/library/pdb.html#pdb.runcall"><em>runcall</em></a><em> which allow you to execute a statement, expression and a function under the debugger control, respectively. One can use them directly from the code or Python interpreter. In my estimation they are pretty much useless, so I’m not covering them. Here is an example usage (straight out of the </em><a href="https://docs.python.org/3.8/library/pdb.html"><em>documentation</em></a><em>):</em></blockquote><pre><strong>&gt;&gt;&gt; import</strong> <strong>pdb</strong><br><strong>&gt;&gt;&gt; import</strong> <strong>mymodule</strong><br><strong>&gt;&gt;&gt; </strong>pdb.run(&#39;mymodule.test()&#39;)<br>&gt; &lt;string&gt;(0)?()<br>(Pdb) continue<br>&gt; &lt;string&gt;(1)?()<br>(Pdb) continue<br>NameError: &#39;spam&#39;<br>&gt; &lt;string&gt;(1)?()<br>(Pdb)</pre><h3>Getting help</h3><p>The first and the last thing one needs when learning a new tool is a good help-system. Like every decent piece of software, pdb has a built-in one. We can access it via <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-help">h(elp)</a> command. To get help on help type: h help:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*2MSX6yGbrtWmdzEyQBvcww.png" /></figure><p>Without arguments, h(elp) prints available commands (see above).</p><h4>Shortening names</h4><p>Please note the brackets around the last part of the command. The brackets indicate that the rest of the word is optional. This can save up a lot of keystrokes. However, you need to remember that commands take precedence over names. In effect, short cryptic variable like b will issue a command (break in this case) instead. Of course, this should not be a problem if your naming hygiene is well-maintained.</p><h4>Command signatures</h4><p>help is here to tell us about commands; but how can we know which commands accept which arguments? What about commands that accept multiple arguments in different forms? What if they are optional? To specify that pdb is using quasi-<a href="https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form">EBNF</a> (it’s not really it, but somewhat similar).</p><p>In short, arguments to commands must be separated by whitespace. Optional arguments are enclosed in square brackets: []. Alternatives in the command syntax are enclosed by parenthesis and separated by a vertical bar:(|).</p><p>Let’s look at the example (nevermind the actual command; we will focus on the notation for now):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*bCOdupa1CF2HmpQV7sHuMQ.png" /></figure><p>What this means is that:</p><ul><li>break can be called with or without any argument — [] means <em>optional</em>.</li><li>break can be given [filename:]lineno or function —( | ) means <em>alternative</em> (here, again, first argument form has an optional part).</li><li>break always accepts zero or more conditions, separated by a comma.</li></ul><h3>Getting things done</h3><p>Here are the absolute basics.</p><h4>Inspection</h4><p>Debugging is all about spying on a running program. For that, we need to able to inspect variables. To evaluate a name, just type it in. If the naming is poor, and the variable clashes with pdb commands, you can use <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-p">p(rint)</a> to explicitly print it. For example:</p><pre>(Pdb) p a_list<br>[&#39;a&#39;, &#39;list&#39;, &#39;of&#39;, &#39;strings&#39;]</pre><p>There is also <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-pp">pp</a> (for <em>pretty print</em>) which takes care of a bit more sane formatting in some cases — for example when printing lists (however, to be honest, I do not remember using it once).</p><p>If you want to quickly print all the arguments passed to the currently inspected function, <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-args">args</a> is your friend:</p><pre>(Pdb) list<br>  1     def foo(spam, ham, eggs)<br>  2         import pdb<br>  3  -&gt;     pdb.set_trace()<br>  4<br>  5<br>  6 foo(1, 2, 3)<br>[EOF]<br>(Pdb) args<br>spam = 1<br>ham = 2<br>eggs = 3</pre><p>*list displays source code. We will talk about it in more depth a bit later.</p><p><a href="https://asciinema.org/a/228089">Inspecting variables</a></p><h4>Interpretation</h4><p>Before we go into topics such as single-stepping or breakpoints, let’s cover features not specific to debuggers.pdb supports expression interpretation (with some restrictions), so any valid Python expression is executable in pdb’s prompt. This allows us to modify the runtime (e.g., by introducing variables or calling functions) and inspecting what’s already available. Please note, however, the usage of the word “expression”. pdb is not a full interpreter, and so multiline statements are out the window. This includes things like class or function declarations (lambdas are ok because they are expressions).</p><pre>(Pdb) 1 / 2 * 3<br>1.5<br>(Pdb) foo = lambda bar: bar * 2<br>(Pdb) foo(&#39;bzz&#39;)<br>bzzbzz</pre><p>If for some reason pdb doesn&#39;t recognize command as a valid Python expression, you can explicitly execute it as such using the bang ! operator:</p><pre>(Pdb) !x, y = 1, 2<br>(Pdb) !x, y = y, x + y</pre><p>*Note the lack of the whitespace after the exclamation mark.</p><h4>Navigation</h4><p>Next, we need to be able to navigate the source code. For that, we will use <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-list">list</a>. Without arguments, list displays 11 lines around the current position in the file or continues going through the previous listing.</p><p>Seems straightforward, except for that last part. It turns out that default list behavior is somewhat counterintuitive — list displays code at the pointer which is shifted down every time the command is called. When executed for the first time, the pointer is taken to be the current position.</p><p>Therefore, if we keep repeating the command, we keep going down through the code. To list the same chunk of code, use l . (there is another fix for this which we will discuss later). You can also specify lines to print, for example list 9 11. Since Python 3.2 we also have ll (or <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-ll">longlist</a>), which displays the whole source code for the current function or a lexical block. When debugging module-level code, this will print the entire file!</p><p>Next up, we have <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-next">n(ext)</a> — execute until the next line is reached or the function returns. This is self-explanatory. However, one big gotcha is that next refers to the next <em>logical</em> line. This means that if we are at the end of the loop body, we will jump to its beginning (given that loop condition holds).</p><p><a href="https://asciinema.org/a/229402">Stepping with next</a></p><p>Stepping through the loop with n(ext) gets tiresome pretty quickly. Luckily, we have <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-until">unt(il)</a> — without argument, it continues the execution until the line with a greater number than the current one is reached. If a line number is specified, continue until that line. This means that when at the end of the loop body, until will not loop around, but instead break out of the loop.</p><p><a href="https://asciinema.org/a/2bqBRzqm42sWKBf8nzA7wMnbg">Stepping in and out of the loop with &quot;until&quot;</a></p><p>If you want to break out of the function, use <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-return">return</a>. It allows following the execution and breaking at the last (logical) statement in the function. If there are multiple return statements, return will stop at the one determined by the control flow. If you want to check the value of the last returned function, use retval.</p><p><a href="https://asciinema.org/a/229409">Skipping the function body with &quot;return&quot;</a></p><p>To continue execution of the program (i.e., to give up the control and effectively end the debugging), use <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-continue">continue</a>.</p><blockquote>Pro-tip<em>: If you started your session via </em><em>set_trace, and the setup line is placed in a loop (or any block of code being called repeatedly), you might easily find yourself caught in a seemingly endless spiral of </em><em>pdb&#39;s prompts. In such case </em><em>continue won’t help you (since it can only refer to the current session, not the future ones). To break out of it, use this hack: </em><em>pdb.set_trace = None</em></blockquote><h4>Jumping around</h4><p>Reversing time and stepping back through program state is called reverse debugging. It’s a very advanced technique and pdb does not support it at the time (although there are some other experimental implementations for Python). Nonetheless, in order to jump back and forth between/through/around executable lines, without resetting the program state, we can use <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-jump">jump</a>. To jump forth, simply type jump specifying the next line that should be executed. Please note that all the lines between the current and the target are not going to be executed. To jump back, use the same format. This time we will move up to line 100. Please note that every line between the current one and the target (which has smaller line number this time around) still remains executed.</p><p><a href="https://asciinema.org/a/229527">Moving up and down with &quot;jump&quot;</a></p><p>To summarize:</p><ul><li>list displays code;</li><li>next continues execution until the next logical step;</li><li>until continues execution until the next physical line;</li><li>continue continues execution indefinitely;</li><li>return jumps to the end of the current function;</li><li>jump allows moving up and down along the executable lines without changing the program state.</li></ul><h4>Breakpoints</h4><p>Before we can really start getting things done, we need one last component — dynamic breakpoints. Until now, we’ve used set_trace to specify where debugger should stop the execution. With <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-break">break</a> we can create breakpoints dynamically, during an active session. Let’s look at the signature one more time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*bCOdupa1CF2HmpQV7sHuMQ.png" /></figure><p>That’s a mouthful, so let’s unpack it. Simplest usage (what you will do most of the time) is just ordering pdb to break at a line. To set a breakpoint, type break &lt;lineno&gt;.</p><p>Additionally, we can specify a filename in which interesting line is located by prepending it to the invocation:</p><pre>(Pdb) break some_file:123</pre><p>If you don’t feel like counting lines, you can use function name:</p><pre>(Pdb) break some_function</pre><p>In such a case, the debugger will stop at the first line of the function body.</p><p>To clear a breakpoint, use <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-clear">clear</a> lineno (clear without any arguments will delete all breakpoints).</p><p>To list all existing breakpoints, simply type break (without any arguments):</p><pre>(Pdb) break<br>Num Type         Disp Enb   Where<br>1   breakpoint   keep yes   /script.py:3<br>2   breakpoint   keep yes   /script.py:5</pre><h4>Conditional breakpoints</h4><p>If you’re interested only in certain conditions when setting up a breakpoint (i.e., conditions under which the debugger should stop), you can specify them as the last argument, condition:</p><pre>(Pdb) b 15, x == 7</pre><p>The above command says that the debugger should stop whenever line 15 is reached and x is equal to 7. In general, all valid expressions are allowed, and all expressions are to be evaluated in the scope in which the breakpoint was defined.</p><p><a href="https://asciinema.org/a/229507">Setting up breakpoints</a></p><h3>Advanced topics</h3><h4>Post-mortem debugging</h4><p><em>Post-mortem debugging</em> is a technique which allows us to debug a crashed program, at the time it died, using its traceback object. Naturally, because it is no longer running, we cannot step through it and are restricted to inspecting the last state of its execution context (which is represented by the traceback).</p><blockquote><strong><em>A traceback</em></strong><em> is a stack trace (a report on the state of the call stack) from the point of an exception handler (code catching the error) down the call chain to the origin of the error (where the exception was thrown).</em></blockquote><p>The usual way of entering post-mortem is via <a href="https://docs.python.org/3.8/library/pdb.html#pdb.pm">pdb.pm()</a> or <a href="https://docs.python.org/3.8/library/pdb.html#pdb.post_mortem">pdb.post_mortem()</a>. Those methods are available when <a href="https://docs.python.org/3/library/sys.html#sys.last_traceback">sys.last_traceback</a> is not null:</p><pre>&gt;&gt;&gt; import script<br>Traceback (most recent call last):<br>  File &quot;script.py&quot;, line 1, in &lt;module&gt;<br>    0/0<br>ZeroDivisionError: division by zero<br>&gt;&gt;&gt; pdb.pm()<br>&gt; &lt;...&gt;/script.py(1)&lt;module&gt;()<br>-&gt; 0/0<br>(Pdb)</pre><p>The catch is, this will only work when Python interpreter is handling the error. (so that last_traceback is properly set up). The following code:</p><pre>try:<br>    0/0<br>except:<br>    import pdb; pdb.pm()</pre><p>will throw an error:</p><pre>Traceback (most recent call last):<br>  File &quot;exc.py&quot;, line 2, in &lt;module&gt;<br>    0/0<br>ZeroDivisionError: division by zero</pre><pre>During handling of the above exception, another exception occurred:</pre><pre>Traceback (most recent call last):<br>  File &quot;exc.py&quot;, line 4, in &lt;module&gt;<br>    import pdb; pdb.pm()<br>  File &quot;/usr/lib/python3.7/pdb.py&quot;, line 1625, in pm<br>    post_mortem(sys.last_traceback)<br>AttributeError: module &#39;sys&#39; has no attribute &#39;last_traceback&#39;</pre><p>Of course, it doesn’t make much sense to enter pm in the <em>except</em> clause anyway.</p><p>Additionally, you can call post_mortem with explicit traceback:</p><pre>pdb.post_mortem(exception_obj.__traceback__)</pre><h4>Traversing the stack</h4><p>So far we’ve only seen navigation around the code and stepping inside functions. However, pdb allows traversing the <a href="https://en.wikipedia.org/wiki/Call_stack">call stack</a> (chain of function calls in the running program). This is very handy when you want to know what function called what, and when. It is achieved with three commands: <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-where">where</a>, <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-up">up</a> and <a href="https://docs.python.org/3.8/library/pdb.html#pdbcommand-down">down</a>.</p><ul><li>where — print the stack trace, with the most recent frame at the bottom.</li><li>up — move to the previous frame in the stack trace.</li><li>down — move to next frame in the stack trace (if applicable).</li></ul><p><a href="https://asciinema.org/a/229529">Moving up and down the stack trace with &quot;up&quot; and &quot;down&quot;</a></p><h4>Remote debugging</h4><p>If you are trying to debug a program running on a distant machine (or one that you have no direct access to), it is often useful to use remote debugging. pdb does not support it out-of-the-box, but luckily we have <a href="https://pypi.org/project/remote-pdb/">remote-pdb</a> package. Setting up a remote session is very simple:</p><pre>&gt;&gt;&gt; import remote_pdb as rpdb                                                                                                                                                                                      <br>&gt;&gt;&gt; rpdb.set_trace(&#39;0.0.0.0&#39;, 46485)                                                                                                                                                                                               <br>CRITICAL:root:RemotePdb session open at 0.0.0.0:46485, waiting for connection ...                                                                                                                                <br>RemotePdb session open at 0.0.0.0:46485, waiting for connection ...</pre><p>As you can see, this opens up a connection on the displayed port (46485). We can connect to it using Telnet:</p><pre>telnet 0.0.0.0 46485<br>Trying 0.0.0.0...<br>Connected to 0.0.0.0.<br>Escape character is &#39;^]&#39;.<br>--Return--<br>&gt; &lt;stdin&gt;(1)&lt;module&gt;()-&gt;None<br>(Pdb)</pre><p>or, from another host:</p><pre>telnet 10.3.39.124 46485</pre><h4>Configuration</h4><p>pdb can be configured via .pdbrc file:</p><blockquote>If a file <em>.pdbrc</em> exists in the user’s home directory or in the current directory, it is read in and executed as if it had been typed at the debugger prompt. This is particularly useful for aliases. If both files exist, the one in the home directory is read first and aliases defined there can be overridden by the local file.</blockquote><p>For details, consult the <a href="https://docs.python.org/3/library/pdb.html?highlight=pdb#debugger-commands">documentation</a>.</p><h4>Extensions</h4><p>As with most open-source software, pdb has community extensions. Their description is beyond the scope of this article, but take a look at <a href="https://pypi.org/project/ipdb/">ipdb</a> and <a href="https://pypi.org/project/pdbpp/">pdb++</a>. One of the best additions to look out for is <em>sticky</em> mode.</p><h3>Summary</h3><p>In conclusion, we’ve looked at all most-used pdb features. We learned:</p><ul><li>different ways of starting a pdb session;</li><li>how to get help;</li><li>how to read command signatures;</li><li>how to inspect variables;</li><li>how to use pdb as an interpreter;</li><li>how to navigate through the code;</li><li>how to inspect the stack;</li><li>how to use breakpoints;</li><li>what is post-mortem debugging;</li><li>how pdb can be utilized to debug remotely;</li><li>how pdb can be configured.</li></ul><p>This should give you a good start in incorporating pdb in your usual Python workflow.</p><p>Thank you for reading! You can find me on <a href="https://github.com/IwoHerka">GitHub</a> or <a href="http://iwoherka.eu/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d4f3b42f3f4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/makimo-on-software-development/https-medium-com-iwoherka-working-with-pdb-in-python-8d4f3b42f3f4">Working with pdb in Python</a> was originally published in <a href="https://medium.com/makimo-on-software-development">Makimo On Software Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>