<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Javier Román on Medium]]></title>
        <description><![CDATA[Stories by Javier Román on Medium]]></description>
        <link>https://medium.com/@javier_roman?source=rss-1a5ec3db9fb5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VDgGeLZUAEcHTonGZ_97ww.jpeg</url>
            <title>Stories by Javier Román on Medium</title>
            <link>https://medium.com/@javier_roman?source=rss-1a5ec3db9fb5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 23:24:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@javier_roman/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Four steps between a PDF and a usable number]]></title>
            <link>https://blog.stackademic.com/four-steps-between-a-pdf-and-a-usable-number-23e0b1dcc6df?source=rss-1a5ec3db9fb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/23e0b1dcc6df</guid>
            <category><![CDATA[document-management]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ocr]]></category>
            <dc:creator><![CDATA[Javier Román]]></dc:creator>
            <pubDate>Tue, 11 Aug 2026 12:17:35 GMT</pubDate>
            <atom:updated>2026-11-10T16:49:19.465Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What building document processing actually costs, and what you can buy instead. For European companies with 10 to 100 people.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NjYzZvILUxmI5BX8v4jwFA.jpeg" /><figcaption><em>A build-vs-buy teardown for European companies with 10 to 100 people, and an honest look at what you can buy instead.</em>A card catalogue at the Indiana State Library. The drawer’s own guide card: “If you do not find here what you want, ask the librarian at the information desk.”</figcaption></figure><p>Document extraction is the business of turning a document into data. A supplier emails a PDF invoice and somebody at the other end types the supplier, the date, the tax and eleven line items into the accounting system. Software can do that typing, once it has worked out what kind of document it is looking at. What makes it worth doing is what comes after: until the data is out of the documents, every question about your own paperwork gets answered by a person opening files one at a time.</p><p>An API that does the extraction costs around fifty dollars a month for five thousand invoices. That number is real, and it is why plenty of companies write their own instead of buying anything. It is also the smallest line in the budget. What follows is the rest of it: the four steps the API doesn’t cover, the four kinds of product you can buy instead, and what the European invoice mandate is quietly doing to the question.</p><h3>OCR reads letters. That was never the problem.</h3><p>You may have been told that this problem was solved years ago, and in a narrow sense it was. OCR, optical character recognition, is the technology that looks at a scan or a photograph of a page and works out which letters and numbers are on it. It turns a picture into text you can search and copy. It has been good enough since around 2010, it is built into your phone and your office scanner, and it costs close to nothing.</p><p>That is where most people’s mental model stops. The problem starts one step later.</p><p>A forty-person company accumulates contracts, payslips, delivery notes, insurance policies, certificates, work orders, technical datasheets, and yes, invoices. They are scattered across three people’s mailboxes, a shared folder, and the laptop of someone who left in 2022. Nobody knows how many there are. When you need the contract signed in 2019, someone goes looking by hand.</p><p>Two things make this urgent right now, and only one of them is the one everybody talks about.</p><p>The first is that invoices are about to stop being PDFs. If you sell in France, from 1 September your systems have to be able to receive invoices as structured data. Belgium switched in January. Poland went live this spring, Germany’s turn comes in 2027, and by 2030 it applies across the EU for cross-border trade. Whatever your accountant has been telling you about this, the deadline is now closer than the average software project.</p><p>The second is that invoices are the small part. Every one of those rules covers exactly one document type. None of them helps you find the lease that renews in November. Hold on to both of these, because together they change the answer at the end.</p><h3>The API works, and it is cheap</h3><p>Azure Document Intelligence, Google Document AI and Amazon Textract all do the same basic thing. You send a PDF, you get JSON back. This is OCR with a schema bolted on, and they are genuinely good at it: the prebuilt models handle a clean supplier invoice better than most people expect. At list price, running 5,000 invoices a month through Azure costs somewhere around $50.</p><p>Fifty dollars, against a five-figure annual quote from a vendor. That’s not a close call, and this is where the build decision gets made in most companies. On the arithmetic as presented, it’s a perfectly sensible decision. The arithmetic is just missing everything else.</p><h3>What the API doesn’t give you</h3><p>Getting from “the letters have been read” to “the data is where it needs to be” takes four steps, and the API covers about one and a half of them. Here is the rest, which is the actual project.</p><p><strong>Sorting the pile.</strong> The API answers questions about a document you already identified. It won’t tell you this PDF is a lease and that one is a calibration certificate. If everything arriving is an invoice, fine. Point it at a shared folder with ten years of history and you need a classifier, somewhere to define what your categories even are, and a plan for the document that belongs to a category nobody has invented yet. You’ll also need splitting, because scanned batches arrive as one 40-page PDF containing eleven separate types of documents.</p><p><strong>Extraction past the prebuilt models.</strong> The prebuilt model gives you the header of a standard business document. The hard part is the line items: variable count, variable layout, descriptions that wrap onto two lines, totals that have to reconcile. And the moment you step outside those standard shapes there’s no prebuilt model at all, so you’re writing a schema per document type by hand and rewriting it the day a supplier changes their template. That maintenance never ends, and I’ve never seen anyone budget for it. There’s a related trap worth designing for: ask a language model for a field that isn’t in the document and it will often invent a convincing one. Getting the system to say “I don’t know” instead is work, and there’s no setting for it.</p><p><strong>Asking it questions afterwards.</strong> This is the step people forget, because the API makes it invisible. You get JSON back for one document. Nobody has answered “which contracts expire before December”, or “what did we spend with this supplier last year”, across forty thousand documents accumulated over a decade. Doing that needs the extractions stored in a way you can query, full-text and semantic search over the originals for everything the extraction didn’t capture, and something that can combine the two and tell you where each number came from. That’s not a feature you bolt on later. It’s a decision you make about how you store everything, on day one, before you’ve extracted anything.</p><p><strong>Everything else that makes it a system.</strong> Storage with whatever retention your jurisdiction demands. Permissions, because not everyone should be able to open payslips. An audit trail tying every figure back to the document and version it came from, which stops being a nice-to-have the first time somebody challenges a number in a report. A connector that lands the data in your ERP in the shape it accepts. Reprocessing when you fix a bug. Monitoring, so you hear about failures before the person waiting for the data does.</p><p>Add it up and the fifty dollars is still real. It is also the smallest line in the budget, and the only one nobody has to maintain.</p><p>The line that should worry you comes later. Ship this and you own a product. Somebody has to understand it, and in eighteen months, when that person leaves, you have to replace them for a role you cannot describe in a job advert, competing for that hire against companies where this is the entire business rather than a side effect of selling something else. If document processing is not what your company does, you are not going to win that competition, and you will not enjoy discovering it while the finance team waits for their data. That is what building actually costs, and it never appears on the estimate.</p><h3>So what can you buy instead?</h3><p>Four different kinds of thing, which turn up in the same search and get compared as if they were alternatives to each other.</p><p><strong>The API pieces.</strong> Google Document AI, Amazon Textract, Azure Document Intelligence and Mindee are cloud services that take a document and return structured data. That’s the whole scope: they are components, not products. What’s interesting is which way they’re moving. Google retired its human-review tooling in January 2025 and shut down its document repository product the same day, and Amazon closed its human-review service to new customers in July 2026. The vendors are retreating toward the pure API and leaving the business layer to whoever integrates it, which is a fairly loud signal about where the work actually is, coming from the people best placed to know. <em>Right for you if you have a development team and want to build exactly what you want.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0NkbsuQs7Nd7R5eEpq7YDw.jpeg" /><figcaption>A module from a Powers-Samas punched card computer, 1960s. A component, not a product. Museums Victoria, CC BY 4.0.</figcaption></figure><p><strong>The invoice specialist.</strong> <a href="https://rossum.ai/">Rossum</a> is a Czech company that has spent a decade on one problem: reading invoices without templates, with a human validation screen on top. It does that exceptionally well, and the validation screen is probably the best in the industry. Two catches. The document types it ships with are <em>invoice, credit note, proforma, debit note, receipt </em>and<em> “other”</em>, which is to say buying-and-selling paperwork; <em>contracts </em>or<em> payslips</em>, for example, aren’t on that list and aren’t coming. Entry is $18,000 a year, and <a href="https://medium.com/www.coupa.com">Coupa</a> bought them in May, which points the roadmap further toward large-account spend management. <em>Right for you if you process invoices at volume and genuinely nothing else.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*bVl15pH7ZrLJrryDbJ-P0Q.jpeg" /><figcaption>An invoice for dressmaking, 7 November 1871. The line items were the hard part then too. Museum of New Zealand Te Papa Tongarewa, CC0.</figcaption></figure><p><strong>The full document platform.</strong> <a href="http://start.docuware.com/">DocuWare</a> is a German document management system, thirty years old, with extraction added on top of the filing: versions, retention, approval routing, signature. Worth knowing before you shortlist it: you can install DocuWare on your own server, but its document AI runs as a cloud service in all three deployment models, per its own documentation, so <em>on-premise</em> doesn’t mean the AI is on your premises. <a href="https://medium.com/www.abbyy.com">ABBYY</a> is the other veteran, reading paper since 1989 and a Gartner Magic Quadrant Leader in this category; if your input is battered scans or <em>handwritten forms</em>, it reads things other engines simply can’t. But ABBYY is an engine that feeds another system rather than somewhere your documents live. Both arrive through a partner or an integrator. <em>Right for you if you need approval and signature routing with retention rules, or if you have IT staff, an integrator and several countries to coordinate.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Xg6B1hjYX776jR7VUeTNw.jpeg" /><figcaption>Archival records at the Clara Thomas Archives. Somewhere to put things is not the same as understanding what is in them. Photo: Anna St.Onge, CC BY-SA 4.0.</figcaption></figure><p><strong>The capture already inside your accounting software.</strong> Your ledger probably ships something that reads supplier bills, and this is patchier than the marketing suggests. <a href="https://www.xero.com/">Xero</a> has no OCR of its own but bundles <a href="https://www.hubdoc.com/">Hubdoc</a> free with every paid plan, and for capturing supplier bills that’s genuinely enough. <a href="https://www.datev.com/">DATEV</a> has a clean native path for the German e-invoice formats and for well-behaved supplier invoices. <a href="https://www.sage.com/es-es/productos/sage-200/?gclsrc=aw.ds&amp;gad_source=1&amp;gad_campaignid=22386537257">Sage 200</a> ships no invoice capture at all in either edition, so you’re buying a third-party add-on and calling it included. What they share is that they’re built around the journal entry. The document goes in, becomes a posting, and effectively disappears. Ask any of them for the lease that renews in November and you’ll get a blank look. <em>Right for you if supplier bills are the whole problem and you need it solved this week.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ry4dyX9txOJ-r6AKFx1bLA.jpeg" /><figcaption>An account book. The document goes in, becomes an entry, and disappears. Wellcome Collection, CC BY 4.0.</figcaption></figure><p>If supplier bills are your whole problem and you’re on Xero, stop reading and go turn on Hubdoc. It’s included, it works, and this article starts being useful to you the day contracts and payslips show up.</p><h3>Who this market is built for</h3><p>Here are the five options side by side, on the four questions that decide this and rarely make it onto a feature list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lINSOPJM8ZNcIrLbSVORww.png" /><figcaption>The five options, on the four questions that actually separate them.</figcaption></figure><p>Read down the last column and a pattern appears that has nothing to do with what any of them can do.</p><p>Rossum starts at $18,000 a year, and that buys invoices. Azure will run inside your own infrastructure, but only on an annual commitment starting at $8,640, which is before anyone has written a line of the system around it. DocuWare and ABBYY both arrive through a partner, so the first step is not a trial. It is a scoping exercise with somebody whose job is to run scoping exercises.</p><p>The API pieces look like the exception and they are the trap. Fifty dollars a month is the lowest entry ticket on the list because it hands you the least. What it leaves out is a developer or two for a couple of quarters, an implementation nobody has scheduled, infrastructure to pay for every month afterwards, and the hiring problem from earlier.</p><p>None of this is unreasonable. These are good products and those numbers are fair for the companies they were designed around: organisations with a procurement function, an IT department and a five-year horizon. <strong>The shape of the sale tells you who that is.</strong> A process that opens with a discovery project is built for a buyer who has people available to be discovered.</p><p>A forty-person distributor has none of that. It has an office manager who has noticed the filing is out of control and a director who will give them an afternoon to look into options. In an enterprise sales motion that buyer is a rounding error, and tends to get treated like one.</p><p>Now put the two things from the opening together, because this is where they land. The mandate is dissolving the one document type every vendor in that table built their demo around: as it comes fully into force, a growing share of your <em>invoices</em> arrive as structured data, and for that share the extraction problem doesn’t get easier, it stops existing, on a published timetable, without you buying anything to make it happen. Nobody is legislating a format for <em>leases, payslips, delivery notes </em>or<em> insurance policies</em>, so the rest of the pile stays exactly as hard as it is today, for as long as your company keeps receiving it. The market is loudest about the part being legislated away and quietest about the part that made you start looking.</p><p>That is the real reason the build option keeps coming back around. Building isn’t cheap, and I hope those four steps settled that. It comes back because at your size, most of the buy column is not really addressed to you.</p><h3>Where Orbidoc fits</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*ieEIc573qfG-Ac_n354P-Q.png" /></figure><p>2is an intelligent document management system built to cover the whole run rather than one step of it. <strong>Documents arrive on their own</strong> from the places they already land, <strong>the shared folder, the office scanner, the mailboxes</strong> where half of them are buried, so nobody has to remember to upload anything. <strong>It takes whatever your company actually receives</strong> instead of one blessed document type, works out what each one is, That means considerably more than four headline fields. It means the line items underneath them, the tables, the rows that repeat, every value typed as a date, an amount, a quantity or a reference, so what the document says becomes something you can add up and filter instead of something a person has to read. Every document and everything extracted from it stays there for as long as you keep them.</p><p>On top of that sits an assistant you ask in plain language, the way you would put the question to a colleague rather than to a search box. What happens next is the work a data analyst would do to answer you properly: choosing which documents qualify, filtering by date or supplier or customer, totalling, averaging, grouping by quarter, comparing one document type against another. When the answer is easier to see than to read, it draws it, so a question about spend by quarter comes back as a chart. Every figure carries the document and the version it was taken from, so you can click through to the page it came off. Questions you used to answer by opening files one at a time you now answer by asking. And when another system needs the data, it goes there without anyone retyping it. Documents live in it and data comes out of it, which sounds obvious and is precisely what this market keeps splitting in two.</p><p><em>Orbidoc is built by Dekano, where I work, so treat this section accordingly. What I have said about the other vendors is all checkable on their own sites, and every one of them got a straight answer about when it is the better choice, including the times that answer wasn’t us.</em></p><p>Rather than list features, here it is against the same four steps the API left you to build, taken in the same order.</p><p><strong>Sorting the pile.</strong> It watches those places continuously and learns your categories as it sees them rather than making you define a list up front. A kind of document it has never seen before becomes a new category instead of an error, which is the case that breaks most classifiers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BlOlyPGZdtfaT7m-m_lcRg.png" /><figcaption>The sources Orbidoc is watching: a shared folder and a mailbox. Nothing gets uploaded by hand.</figcaption></figure><p><strong>Extraction.</strong> It works out which fields a category of document has by reading the ones you already have, and updates that template when a supplier changes their layout. Then it fills it in from everything that arrives, line items included. It keeps every version. And when a field isn’t in the document, it says so instead of inventing one.</p><p><strong>Asking it questions afterwards.</strong> You ask it the way you would ask someone on your team, and it organises the work itself: it looks at what document types you hold and what each one records, goes and gets the data, and comes back over its own result to narrow it down or cross it against another type of document. It keeps stepping until the figure comes out of the data rather than out of its own judgement, and every figure it gives you names the document it came from.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_M4kBuMmztdOkKN2P_IZVQ.png" /><figcaption>Left, one explorer holding invoices, safety data sheets, payslips and contracts. Right, the assistant answering “how much have we invoiced with reagent suppliers?”: a real aggregation over the 7 invoices it names, with the chart it produced.</figcaption></figure><p><strong>Everything else that makes it a system.</strong> Getting data out runs through a visual editor where you drag boxes and connect them: read a document type, filter it, have the AI sort a free-text line into a category you defined, join it against another type, export it in the shape your ERP accepts. You build it once and the system does the running from then on, having another go by itself when something fails and telling you when it can’t. Nobody writes code at any point, which is the whole point if this isn’t your line of work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UH4L8_M-bFCi9MwqhMJd2g.png" /><figcaption>Automation editor — purchase invoices are matched against A3ERP suppliers by tax ID and exported as the XLSX file that A3 imports.</figcaption></figure><p>Three things sit outside that checklist and are worth saying anyway. <strong>On the mandate</strong>, the electronic invoice it issues today is the Spanish format, digitally signed with your own certificate. Each format is one file inside the export layer, so another country’s is the same piece of work in the same place rather than a different product. Whoever you buy from, ask them how a new format gets added, because sooner or later you’ll need one that nobody has on their list today.</p><p><strong>On where it runs</strong>, there are three answers and you pick one. <strong>Installed on your own server</strong> with the models running inside it too, no route out to the internet, so the document never leaves your network. <strong>Installed on your own server but pointed at a cloud model</strong>, when you want the quality of the large models and your documents aren’t the sensitive kind. <strong>Or fully hosted by us</strong>, nothing to install at all.</p><p><strong>On price</strong>, there is no public number yet, and I’m not going to present that as a virtue. What I can tell you is the shape of it, which after that last section is the part that actually differs. It scales with how many documents you put through it and how many people use it, so a company filing two hundred documents a month and one filing five thousand are not paying the same thing. One contract covers every document type instead of one product per use case, there’s no partner you’re obliged to go through, and getting to a number is a conversation about your pile rather than a discovery project you have to schedule and staff.</p><p><strong>Choose Orbidoc if your pile is a mess of different document types, your team is administrative rather than technical, and the documents need to stay yours.</strong> Process nothing but invoices at volume? Buy the specialist, once you’ve worked out what the mandate leaves it doing in five years. Need approval and signature routing? Buy the platform. Got a dev team and an appetite? At least now you’ve got the full list of what you’d be building, including the part about who maintains it in 2028.</p><p><em>Checked against each vendor’s own documentation and official EU sources on 7 August 2026. Dollar figures are worth confirming in euros. All trademarks belong to their owners.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23e0b1dcc6df" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/four-steps-between-a-pdf-and-a-usable-number-23e0b1dcc6df">Four steps between a PDF and a usable number</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Say Goodbye to Type Errors: Enforcing Python Types with Decorators]]></title>
            <link>https://blog.stackademic.com/say-goodbye-to-type-errors-enforcing-python-types-with-decorators-497d51851a10?source=rss-1a5ec3db9fb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/497d51851a10</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[decorators]]></category>
            <dc:creator><![CDATA[Javier Román]]></dc:creator>
            <pubDate>Wed, 06 Nov 2024 19:05:54 GMT</pubDate>
            <atom:updated>2024-11-07T01:52:22.908Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>While dynamic type checking in Python offers flexibility, it introduces challenges like runtime errors, reduced readability, and maintenance complexity. Python’s type hints help, but without enforcement, runtime issues can still arise. In this post, we explore using decorators to enforce type hints and ensure strict type adherence.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jxbwH7kG07zq8-53JLgRmg.png" /></figure><p>Python is known for its flexibility and ease of use, largely due to its <strong>dynamic typing system</strong>. This system allows developers to write code without specifying types upfront, validating types during runtime instead of compile time. However, this flexibility can lead to challenges such as runtime errors, reduced code readability, and increased maintenance complexity in larger projects.</p><h3>Python type hints</h3><p>Python introduced type hinting in version 3.5 through <a href="https://peps.python.org/pep-0484/"><strong>PEP 484</strong></a>. The primary reason for this addition was to standardize the annotation syntax which was added in <a href="https://peps.python.org/pep-3107/"><strong>PEP 3107</strong></a> fulfilling the <a href="https://www.artima.com/weblogs/viewpost.jsp?thread=85551">implicit goal the community had</a> of using it for type hinting opening up Python to easier static analysis/refactoring and potential runtime type checking.</p><p>After this feature was released we could define a function like follows:</p><pre>from datetime import datetime, timedelta <br>def add_days(date: datetime, days: int) -&gt; datetime:<br>  &quot;&quot;&quot;Add a number of days to the date.&quot;&quot;&quot; <br>  return date + timedelta(days=days)</pre><p>This helps both human readers and tools (such as static type checkers like mypy) understand how the code is intended to be used.</p><p>However, as <a href="https://peps.python.org/pep-0484/"><strong>PEP 484</strong></a> clarifies, this feature was not designed to enforce types at runtime but rather serves solely for annotation and static type checkers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*FSigUopR8t-PsxAfeFNnUg.png" /><figcaption>PEP 484 explaining what<strong> type hinting</strong> feature <strong>is not</strong> intended for</figcaption></figure><p>This means that even though type hints may improve readability, they do not guarantee that variable types are correct. This can lead to the following situation.</p><blockquote>Imagine you have a simple program that requests two numbers as user input and then sums them:</blockquote><pre>def add(a: int, b: int) -&gt; int:<br>    return a + b<br># Requesting user input for two numbers<br>num1 = input(&quot;Enter the first number: &quot;)<br>num2 = input(&quot;Enter the second number: &quot;)<br># Using the add function to add the numbers<br>result = add(num1, num2)<br># Displaying the result<br>print(f&quot;The sum of {num1} and {num2} is {result}&quot;)</pre><blockquote>However, in this simple program, <strong>we intentionally forgot to cast the user input from <em>str</em> to <em>int</em></strong>.</blockquote><p>Now the user is going to use our program to do some sums and…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*NfvwptTxx5XHUm8ceQ5PCA.gif" /></figure><blockquote><strong>WOW!</strong> We have just reinvented math! <strong>1 + 2 = 12</strong>. I hope your children never use this calculator to do homework.</blockquote><p>This happens because Python does not enforce types, even if we annotate the function arguments. We can still pass two strings thinking we are passing two integers, and Python won’t complain.</p><h3>Enforcing types ourselves</h3><p>The solution must come from ourselves. In the previous <a href="https://peps.python.org/pep-0484/"><strong>PEP 484</strong></a><strong> screenshot </strong>I referenced clearly says <em>“While the proposed typing module will contain some building blocks for runtime type checking … third party packages would have to be developed …, for example using decorators or metaclasses”.</em></p><p>So it’s time to implement this decorator.</p><pre>def enforce_types(func):<br>  def wrapper(*args, **kwargs):<br>    # Get arguments type hints<br>    type_hints = get_type_hints(func)<br>    # Get return type hint<br>    return_hint = type_hints.pop(&#39;return&#39;)<br>    for i, (key, hint) in enumerate(type_hints.items()):<br>      try:<br>       value = kwargs.get(key, args[i])<br>       assert isinstance(value, hint), f&quot;Argument {key} must be of type {hint} but {value=} of type={type(value)} provided&quot;<br>      except IndexError:<br>        pass<br>    result = func(*args, **kwargs)<br>    assert isinstance(result, return_hint)<br>    return result<br>  return wrapper</pre><p>Let’s break it down:</p><ul><li>First we get the type hints of our function. We separate the arguments hints that will be stored in type_hints from the return type that will be stored under return_hint</li></ul><pre>type_hints = get_type_hints(func) <br>return_hint = type_hints.pop(&#39;return&#39;)</pre><ul><li>After this we iterate over all argument hints in order and we extract their values, which can come from either <em>kwargs</em> or under <em>args</em>. If it is not found under <em>kwargs </em>we default to the position of the argument inside of <em>args</em> to get its value. If there’s no such an element inside <em>args</em> it will raise an IndexError that we will ignore as calling our decorater function will complain raising a TypeError .</li></ul><pre>for i, (key, hint) in enumerate(type_hints.items()):<br>  try:<br>    value = kwargs.get(key, args[i])<br>    ...<br>  except IndexError:<br>     pass</pre><ul><li>Now we check for each argument value that its type is the same as the hint.</li></ul><pre>assert isinstance(value, hint), f&quot;Argument {key} must be of type {hint} but {value=} of type={type(value)} provided&quot;</pre><ul><li>After this we call our function and check the return type.</li></ul><pre>result = func(*args, **kwargs)<br>assert isinstance(result, return_hint), f&quot;Return type must be a {return_hint} but {type(result)} was returned&quot;<br>return result</pre><h4>Let’s use our decorator!</h4><p>Now we can use this <strong>decorator</strong> with our previously implemented <strong>calculator</strong></p><pre>@enforce_types<br>def add(a: int, b: int) -&gt; int:<br>    return a + b<br># Requesting user input for two numbers<br>num1 = input(&quot;Enter the first number: &quot;)<br>num2 = input(&quot;Enter the second number: &quot;)<br># Using the add function to add the numbers<br>result = add(num1, num2)<br># Displaying the result<br>print(f&quot;The sum of {num1} and {num2} is {result}&quot;)</pre><p>Following the decoration of our add function, the user will not be able to perform the addition without fixing the error of not casting the input back to an integer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9GtwJFVZzjogig-13Ae4Qw.gif" /></figure><h3>Other libraries</h3><p>If implementing your own type-enforcing decorator feels too complex or time-consuming, there are various libraries available that can simplify this task.</p><p>The most well-known library for type checking and validation is Pydantic. It comes with the built-in decorator @validate_call, which replicates the functionality we implemented above, providing an easy and efficient way to enforce types at runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*SwftVMonSX_x12dRbVKzbg.png" /><figcaption><em>We use ConfigDIct(strict=True) because otherwise it won’t fail as pydantic tries to convert the string to integer before validation.</em></figcaption></figure><p>If you don’t like pydantic there are many other libraries out there that already implement this:</p><ul><li>Beartype</li><li>Typeguard</li><li>Enforce</li></ul><h3><strong>Wrapping Up</strong></h3><p>In this article, we explored how Python, despite its flexibility with dynamic type checking, can benefit from implementing runtime type enforcement.</p><p>We discussed how type hints enhance code readability and support static analysis, but don’t guarantee type validity at runtime. We looked at how a custom decorator can help enforce type annotations and mentioned robust tools like Pydantic that offer built-in solutions for this purpose.</p><p>By adding this layer of type enforcement, you can catch potential issues early and maintain cleaner, more reliable code. Give it a shot and see the difference it makes in your development process!</p><h3>If You Wish To Support Me As A Creator</h3><p>Thank you for reading! If you found this post helpful or interesting, please share it with others who might benefit from it and hit the applause 👏🏼 button. Also if you have any thoughts or experiences with type enforcement, feel free to share them in the comments below.</p><p>Your support helps spread knowledge and innovation within the developer community.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=497d51851a10" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/say-goodbye-to-type-errors-enforcing-python-types-with-decorators-497d51851a10">Say Goodbye to Type Errors: Enforcing Python Types with Decorators</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Singletons Simplified: A fresh Python approach for modern developers]]></title>
            <link>https://blog.stackademic.com/singletons-simplified-a-fresh-python-approach-for-modern-developers-62358a25e3af?source=rss-1a5ec3db9fb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/62358a25e3af</guid>
            <category><![CDATA[decorators-in-python]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Javier Román]]></dc:creator>
            <pubDate>Mon, 01 Jul 2024 08:39:25 GMT</pubDate>
            <atom:updated>2024-07-03T00:07:56.655Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qfLUXc9bPEFr35et" /><figcaption>Photo by <a href="https://unsplash.com/@afgprogrammer?utm_source=medium&amp;utm_medium=referral">Mohammad Rahmani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>What if I told you that you could create a singleton pattern </em><strong><em>using nothing more than a decorator?</em></strong></p><p><strong><em>That’s right!</em></strong><em> Just one simple decorator. And no, it’s not the usual </em><em>@singleton that most tutorials push you to implement. Instead, you can achieve the singleton pattern </em><strong><em>using Python’s </em></strong><strong><em>@cache decorator.</em></strong></p><p><em>But first, let’s go over some definitions.</em></p><h3><strong>What is a singleton?</strong></h3><p>Singletons are a well-known software design pattern used to ensure a class has only one instance. This is particularly useful when a single object is needed to coordinate actions within a system.</p><p>The most common way to implement a Singleton in Python is by using the __new__ method.</p><pre>class MySingleton:<br>    _instance = None<br><br>    def __new__(cls, *args, **kwargs):<br>        if cls._instance is None:<br>            cls._instance = super().__new__(cls, *args, **kwargs)<br>        return cls._instance</pre><p>^ Basically, this implementation checks if the instance of the class exists every time__new__is called. If the instance already exists, it is returned; otherwise, it is instantiated and stored for future calls.</p><p><strong>Wait!</strong> But why do we use __new__ instead of __init__ ?</p><p><strong>Good question</strong>. This is something I wondered myself before knowing the answer.</p><p>In Python __new__ and __init__ are both special methods that participate in python’s object creation process.</p><ul><li>__new__ is a <em>class method</em> and the first step in the class instantiation process. It takes a class (typically named cls) and returns an instance.</li><li>On the other hand, __init__ is responsible for initializing the instance attributes. This means the instance already exists when __init__ is called. The instance is typically passed to the method as an argument called self , which we’re all familiar with.</li></ul><p>Thus, to properly create a singleton, the only place to do it is right where the instance is created. Otherwise, we could not check if the instance already exists.</p><p>When we instantiate this class multiple times, we can observe that the singleton pattern ensures the class instance remains consistent, no matter how many times the constructor is called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*zHWw5IzJkXFE_p_apPKdRg.png" /></figure><p>This consistency wouldn’t hold for a class that doesn’t implement the singleton pattern. In such cases, every call to the constructor would create a new instance of the class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*KmRYGHtnPg4T13ZLBhig8g.png" /></figure><h3>What is a decorator?</h3><p>In Python, a decorator is a design pattern that allows you to add new functionality to an existing function or class without modifying its structure. A decorator takes a function as an argument, wraps it in another function that adds the new functionality, and returns the wrapped function.</p><p>Here’s a simple example:</p><pre>def my_decorator(func):<br>    def wrapper():<br>        print(&quot;Something is happening before the function is called.&quot;)<br>        func()<br>        print(&quot;Something is happening after the function is called.&quot;)<br>    return wrapper<br><br>@my_decorator<br>def say_hello():<br>    print(&quot;Hello!&quot;)<br><br>say_hello()<br><br>### Output<br># &gt;&gt;&gt; say_hello()<br># Something is happening before the function is called.<br># Hello!<br># Something is happening after the function is called.</pre><p>Decorators are incredibly useful for a variety of tasks such as logging, enforcing access control, instrumentation, and caching, among others.</p><p>Additionally, we can even decorate classes since they are callable objects in Python:</p><pre>@my_decorator<br>class MyDecoratedClass:<br>    def __init__(self, n):<br>        self.n = n<br>        print(f&quot;Value is {n}&quot;)<br><br>### Output<br># &gt;&gt;&gt; MyDecoratedClass(1)<br># Something is happening before the function is called.<br># Value is 1<br># Something is happening after the function is called.</pre><h4>The cache decorator</h4><p>The <em>cache</em> decorator was introduced in Python 3.9 as part of the <em>functools</em> module. It allows you to cache the results of a function, meaning that if the function is called again with the same arguments, the cached result is returned instead of recomputing it.</p><p>You might have seen this in various Fibonacci implementation tutorials on Medium, demonstrating how the use of cachecan significantly enhance performance by avoiding redundant calculations.</p><p>This optimization technique is called <strong>memoization</strong>.</p><pre>from functools import cache<br><br>@cache<br>def cache_fibonacci(n):<br>    if n &lt; 2:<br>        return n<br>    return cache_fibonacci(n - 1) + cache_fibonacci(n - 2)<br><br>###  Output<br># &gt;&gt;&gt; no_cache_fibonacci(35)<br># 9227465 # Time: 1.22s<br># &gt;&gt;&gt; cache_fibonacci(35)<br># 9227465 # Time: 0.0000398s</pre><p>^ As you can see, cache drastically reduces the computation time by storing previously computed results and reusing them for subsequent calls with the same arguments.</p><p><a href="https://medium.com/@pvsravanth/speeding-up-your-python-code-with-the-cache-decorator-from-functools-bce4731eed69">Speeding Up Your Python Code with the cache Decorator from functools</a></p><h3>Using the cache decorator to implement a singleton</h3><p>Now that we understand what a singleton is, how decorators work over classes, and how the cache decorator stores the result of a function call and returns it if the same function call happens again, we can use it to implement the singleton pattern.</p><p>The implementation is as easy as follows:</p><pre>from functools import cache<br><br>@cache<br>class MySingleton:<br>    pass</pre><p>^ By simply applying the @cache decorator to our class, we have effectively implemented a singleton in a more concise and less verbose manner, keeping our code cleaner.</p><p>This approach leverages the caching mechanism to ensure that only one instance of the class is created, achieving the same result as the traditional singleton implementation but with much simpler code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*VRqLO_ybxf5chiSeNw71cQ.png" /><figcaption>As you can see above even though I’ve instantiated the class twice the instance keeps the same.</figcaption></figure><h3><strong>Limitations with this approach</strong></h3><p>While this approach offers a clean and concise way to implement a Singleton, there are two important limitations you should be aware of before using it.</p><h4><strong>Issue 1: Semantic problem</strong></h4><p>The first issue is a semantic one and it arises when your class has arguments in its constructor:</p><pre>from functools import cache<br><br>@cache<br>class MySingleton:<br>    def __init__(self, a):<br>        self.a = a</pre><p>Calling the class constructor with the same argument will return the same instance, but calling it with different arguments will create different instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*7twzxY65hECCKBi8HduFIQ.png" /></figure><p>The problem here is that the implementation does not purely follow the singleton pattern but rather the <strong>multiton pattern</strong>.</p><p><strong>What is the multiton pattern?</strong></p><p>The multiton pattern is a design pattern that extends the singleton pattern. It ensures that the same instance is returned every time the constructor is called with the same set of arguments, but different instances are created for different sets of arguments.</p><p>This pattern can be particularly useful in scenarios such as managing connections to multiple databases, where you want a unique instance for each database.</p><pre>from functools import cache<br><br>@cache<br>class MultitionDatabaseConnection<br><br>    def __init__(self, db_name):<br>        self.db_name = db_name<br><br>    def connect_to_database(self):<br>        print(f&quot;Connecting to database: {self.db_name}&quot;)<br><br>    def query(self, sql):<br>        print(f&quot;Executing query on {self.db_name}: {sql}&quot;)<br><br>db1 = MultitionDatabaseConnection(&#39;database1&#39;)<br>db2 = MultitionDatabaseConnection(&#39;database1&#39;)<br>db3 = MultitionDatabaseConnection(&#39;database2&#39;)<br><br>print(db1 is db2)  # Output: True<br><br>print(db1 is db3)  # Output: False</pre><p>^ In the example above every time we instantiate a MultitionDatabaseConnection with the database name database1, we get the same instance. However if we instantiate one with a different name we would get a different instance.</p><p><strong>Issue 2: Inheritance</strong></p><p>The second limitation involves inheritance. When you create a singleton, you might want to create a child class. This is possible with the traditional implementation:</p><pre>class ClassSingleton:<br>     _instance = None<br><br>     def __new__(cls, *args, **kwargs):<br>         if cls._instance is None:<br>             cls._instance = super().__new__(cls, *args, **kwargs)<br>         return cls._instance<br><br>class ClassSingletonChild(ClassSingleton):<br>     pass<br><br>a = ClassSingletonChild()<br>b = ClassSingletonChild()<br><br>print(a is b) # Output: True</pre><p>^ In the example above, you can see how the child class inherits the singleton properties.</p><p>However, when using the cache approach, implementing a child class is not possible:</p><pre>from functools import cache<br><br>@cache<br>class DecoratorSingleton:<br>     pass<br><br><br>class DeocratorSingletonChild(DecoratorSingleton):<br>     pass<br><br># Output<br># ---------------------------------------------------------------------------<br># TypeError                                 Traceback (most recent call last)<br># Cell In[9], line 1<br># ----&gt; 1 class DeocratorSingletonChild(DecoratorSingleton):<br>#       2     pass<br><br># TypeError: lru_cache() missing required argument &#39;cache_info_type&#39; (pos 4)</pre><p>^ This happens because when we use the cache decorator over a class, its definition becomes a function rather than a class, and we lose the ability to implement child classes.</p><pre>&gt;&gt;&gt; ClassSingleton<br>__main__.ClassSingleton<br><br>&gt;&gt;&gt; DecoratorSingleton<br>&lt;functools._lru_cache_wrapper at 0x104fd0a90&gt;</pre><p>^ As shown, the DecoratorSingleton is transformed into a function wrapped by the cache decorator, thus preventing inheritance.</p><h3>Conclusions</h3><p>Despite the limitations we’ve discussed, using the cache decorator to implement singletons or multiton patterns in Python is a fascinating and innovative approach. This method offers a cleaner and more concise way to achieve these patterns, which can lead to more readable and maintainable code.</p><p>If you understand and accept the limitations — such as issues with constructor arguments and inheritance — this approach can be a valuable tool in your Python toolkit. It demonstrates the power and flexibility of Python’s decorator system, allowing you to leverage built-in functionalities in creative ways.</p><p>In summary, while the traditional methods of implementing singletons may provide more control and flexibility, the cache decorator offers an elegant alternative for those looking to keep their codebase streamlined. As with any tool, the key is to understand its strengths and weaknesses and use it appropriately based on the needs of your project.</p><p>Thank you for reading! If you found this post helpful or interesting, please share it with others who might benefit from it and hit the applause button. Also if you have any thoughts or experiences with this pattern, feel free to share them in the comments below.</p><p>Your support helps spread knowledge and innovation within the developer community.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62358a25e3af" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/singletons-simplified-a-fresh-python-approach-for-modern-developers-62358a25e3af">Singletons Simplified: A fresh Python approach for modern developers</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>