
    
        
        
        
                
        
        
        
                
        
        
        
                
        
        
        
                
        
        
        
            
{"version":"https:\/\/jsonfeed.org\/version\/1","title":"mathspp.com feed","home_page_url":"https:\/\/mathspp.com\/blog\/tags\/fp","feed_url":"https:\/\/mathspp.com\/blog\/tags\/fp.json","description":"Stay up-to-date with the articles on mathematics and programming that get published to mathspp.com.","author":{"name":"Rodrigo Gir\u00e3o Serr\u00e3o"},"items":[{"title":"Functions: a complete reference | Pydon&#039;t \ud83d\udc0d","date_published":"2025-10-06T09:00:00+02:00","id":"https:\/\/mathspp.com\/blog\/pydonts\/functions-a-complete-reference","url":"https:\/\/mathspp.com\/blog\/pydonts\/functions-a-complete-reference","content_html":"<p>This article serves as a complete reference for all the non-trivial things you should know about Python functions.<\/p>\n\n<p>Functions are the basic building block of any Python program you write, and yet, many developers don't leverage their full potential.\nYou will fix that by reading this article.<\/p>\n<p>Knowing how to use the keyword <code>def<\/code> is just the first step towards knowing how to define and use functions in Python.\nAs such, this Pydon't covers everything else there is to learn:<\/p>\n<ul><li>\n<a href=\"#what-goes-into-a-function-and-what-doesn-t\">How to structure and organise functions<\/a>.<\/li>\n<li>\n<a href=\"#the-function-signature\">How to work with a function signature<\/a>, including <a href=\"#ordering-the-parameters\">parameter order<\/a>, <a href=\"#args-and-kwargs\"><code>*args<\/code> and <code>**kwargs<\/code><\/a>, and <a href=\"#positional-only-and-keyword-only-arguments\">the special syntax introduced by <code>*<\/code> and <code>\/<\/code><\/a>.<\/li>\n<li>\n<a href=\"#documenting-functions-with-docstrings\">Best practices to document a function<\/a>.<\/li>\n<li>\n<a href=\"#anonymous-functions\">What anonymous functions are<\/a>, how to define them with the keyword <code>lambda<\/code>, and <a href=\"#use-case-rule-of-thumb\">when to use them<\/a>.<\/li>\n<li>\n<a href=\"#functions-as-objects\">What it means for functions to be objects<\/a> and how to leverage that in your code.<\/li>\n<li>\n<a href=\"#closures\">How closures seem to defy a fundamental rule of scoping in Python<\/a>.<\/li>\n<li>\n<a href=\"#decorators\">How to leverage closures to create the decorator pattern<\/a>.<\/li>\n<li>\n<a href=\"#generator-functions\">What the keyword <code>yield<\/code> is and what generator functions are<\/a>.<\/li>\n<li>\n<a href=\"#asynchronous-functions\">What the keyword <code>async<\/code> is and what asynchronous functions are<\/a>.<\/li>\n<li>\n<a href=\"#partial-function-application\">How partial function application allows you to create new functions from existing functions<\/a>.<\/li>\n<li>\n<a href=\"#not-all-functions-are-functions\">How the term &ldquo;function&rdquo; is overloaded<\/a> and how you can <a href=\"#creating-your-own-callables\">create your own objects that behave like functions<\/a>.<\/li>\n<\/ul><!--v--><div class=\"notices blue\">\n<p>Bookmark this reference for later or download the <a href=\"\/books\/pydonts\">&ldquo;Pydon'ts &ndash; write elegant Python code&rdquo;<\/a> ebook for free.\nThe ebook contains this chapter and many others, including hundreds of tips to help you write better Python code.\n<a href=\"\/books\/pydonts\">Download the ebook &ldquo;Pydon'ts &ndash; write elegant Python code&rdquo; here<\/a>.<\/p>\n<\/div>\n<!--^-->\n<h2 id=\"what-goes-into-a-function-and-what-doesn-t\">What goes into a function and what doesn't<a href=\"#what-goes-into-a-function-and-what-doesn-t\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>Do not overcrowd your functions with logic for four or five different things.\nA function should do a single thing, and it should do it well, and the name of the function should clearly tell you what your function does.<\/p>\n<p>If you are unsure about whether some piece of code should be a single function or multiple functions, it's best to err on the side of too many functions.\nThat is because a function is a modular piece of code, and the smaller your functions are, the easier it is to compose them together to create more complex behaviours.<\/p>\n<p>Consider the function <code>process_order<\/code> defined below, an exaggerated example that breaks these best practices to make the point clearer.\nWhile it is not incredibly long, it does too many things:<\/p>\n<pre><code class=\"language-py\">def process_order(order):\n    # Validate the order:\n    for item, quantity, price in order:\n        if quantity &lt;= 0:\n            raise ValueError(f\"Cannot buy 0 or less of {item}.\")\n        if price &lt;= 0:\n            raise ValueError(f\"Price must be positive.\")\n\n    # Write the receipt:\n    total = 0\n    with open(\"receipt.txt\", \"w\") as f:\n        for item, quantity, price in order:\n            # This week, yoghurts and batteries are on sale.\n            if \"yoghurt\" in item:\n                price *= 0.8\n            elif \"batteries\" in item:\n                price *= 0.5\n            # Write this line of the receipt:\n            partial...<\/code><\/pre>","summary":"This article is a complete reference for all things related to functions in Python","date_modified":"2025-11-14T12:17:33+01:00","tags":["fp","programming","python"],"image":"\/user\/pages\/02.blog\/02.pydonts\/functions-a-complete-reference\/thumbnail.webp"},{"title":"functools.Placeholder","date_published":"2025-08-22T21:21:00+02:00","id":"https:\/\/mathspp.com\/blog\/how-to-use-functools-placeholder","url":"https:\/\/mathspp.com\/blog\/how-to-use-functools-placeholder","content_html":"<p>Learn how to use <code>functools.Placeholder<\/code>, new in Python 3.14, with real-life examples.<\/p>\n\n<p>By reading this article you will understand what <code>functools.Placeholder<\/code> is for and how to use it effectively.<\/p>\n<h2 id=\"partial-function-application\">Partial function application<a href=\"#partial-function-application\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>The new <code>Placeholder<\/code>, added in Python 3.14, only makes sense in the context of <code>functools.partial<\/code>, so in order to understand <code>Placeholder<\/code> you will need to <a href=\"\/blog\/functools-partial\">understand how <code>functools.partial<\/code> works and how to use it<\/a>.<\/p>\n<p>In a nutshell, <code>partial<\/code> allows you to perform partial function application, by &ldquo;freezing&rdquo; arguments to functions.<\/p>\n<h2 id=\"how-to-pass-arguments-to-functools-partial\">How to pass arguments to <code>functools.partial<\/code><a href=\"#how-to-pass-arguments-to-functools-partial\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>Up until Python 3.13, you could use <code>partial<\/code> to freeze arguments in two types of ways:<\/p>\n<ol><li>you could pass positional arguments to <code>partial<\/code>, which would be passed in the same order to the function being used with <code>partial<\/code>; or<\/li>\n<li>you could pass keyword arguments to <code>partial<\/code>, which would be passed with the same name to the function being used with <code>partial<\/code>.<\/li>\n<\/ol><h2 id=\"using-keyword-arguments-to-skip-the-first-argument\">Using keyword arguments to skip the first argument<a href=\"#using-keyword-arguments-to-skip-the-first-argument\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>The method 2. is especially useful if you're trying to freeze an argument that is not the first one.\nFor example, if you use the built-in <code>help<\/code> on the built-in <code>int<\/code>, you can see this signature:<\/p>\n<pre><code>int(x, base=10) -&gt; integer<\/code><\/pre>\n<p>If you want to convert a binary string to an integer, you can set <code>base=2<\/code>:<\/p>\n<pre><code class=\"language-py\">print(int(\"101\", 2))  # 5<\/code><\/pre>\n<p>Now, suppose you want to create a function <code>from_binary<\/code> by &ldquo;freezing&rdquo; the argument <code>2<\/code> in the built-in <code>int<\/code>.\nWriting<\/p>\n<pre><code class=\"language-py\">from_binary = partial(int, 2)<\/code><\/pre>\n<p>won't work, since in <code>partial(int, 2)<\/code>, the value <code>2<\/code> is seen as the argument <code>x<\/code> from the signature above.\nHowever, you can pass the base as a keyword argument, skipping the first argument <code>x<\/code> from the signature of the built-in <code>int<\/code>:<\/p>\n<pre><code class=\"language-py\">from functools import partial\n\nfrom_binary = partial(int, base=2)\n\nprint(from_binary(\"101\"))  # 5<\/code><\/pre>\n<p>But this doesn't always work.<\/p>\n<h2 id=\"when-keyword-arguments-don-t-work\">When keyword arguments don't work<a href=\"#when-keyword-arguments-don-t-work\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>Consider the following function that <a href=\"\/blog\/pydonts\/string-translate-and-maketrans-methods\">uses the string methods <code>maketrans<\/code> and <code>translate<\/code><\/a> to strip punctuation from a string:<\/p>\n<pre><code class=\"language-py\">import string\n\n_table = str.maketrans(\"\", \"\", string.punctuation)\ndef remove_punctuation(string):\n    return string.translate(_table)\n\nprint(remove_punctuation(\"Hello, world!\"))  # Hello world<\/code><\/pre>\n<p>The function <code>remove_punctuation<\/code> is a thin wrapper around the string method <code>str.translate<\/code>, which is the function doing all the work.\nIn fact, if you look at <code>str.translate<\/code> as a function, you always pass <code>_table<\/code> as the second argument; what changes is the first argument:<\/p>\n<pre><code class=\"language-py\">print(str.translate(\"Hello, world!\", _table))  # Hello world\nprint(str.translate(\"What?!\", _table))  # What<\/code><\/pre>\n<p>This may lead you to wanting to use <code>partial<\/code> to freeze the value <code>_table<\/code> on the function <code>str.translate<\/code>, so you use the built-in <code>help<\/code> to check the signature of <code>str.translate<\/code>:<\/p>\n<pre><code>translate(self, table, \/) unbound builtins.str method<\/code><\/pre>\n<p>You can see that the first argument is <code>self<\/code>, the string you are trying to translate, and then <code>table<\/code> is the translation table (that <code>str.maketrans<\/code> built magically for you).\nBut you can also see the forward slash <code>\/<\/code>, which means that <code>self<\/code> and <code>table<\/code> are positional-only arguments that cannot be passed in as keyword arguments!<\/p>\n<p>As such,...<\/p>","summary":"Learn how to use `functools.Placeholder`, new in Python 3.14, with a real-life example.","date_modified":"2025-08-22T23:09:02+02:00","tags":["python","programming","fp"],"image":"\/user\/pages\/02.blog\/functools-placeholder\/thumbnail.webp"},{"title":"Decorators | Pydon&#039;t \ud83d\udc0d","date_published":"2025-01-21T18:11:00+01:00","id":"https:\/\/mathspp.com\/blog\/pydonts\/decorators","url":"https:\/\/mathspp.com\/blog\/pydonts\/decorators","content_html":"<p>This article teaches the decorator pattern in Python, why it exists, how to use it, and when to use it to write efficient and idiomatic Python code.<\/p>\n\n<p>The decorator pattern is a functional pattern that Python developers leverage to write more modular and composable functions.\nIn this Pydon't, you will learn exactly why the decorator pattern matters, how to use it, and when to use it.\nYou will also learn how to implement your custom decorators and more advanced use cases of decorators.<\/p>\n<p>In this Pydon't, you will:<\/p>\n<ul><li>learn to recognise when a decorator must be used;<\/li>\n<li>learn to identify the functionality that should be extracted into a decorator;<\/li>\n<li>use an analogy to understand what a decorator is;<\/li>\n<li>implement two simple decorators as initial examples;<\/li>\n<li>learn the full anatomy of a general decorator;<\/li>\n<li>understand why <code>functools.wraps<\/code> should be used when defining decorators;<\/li>\n<li>add arguments to your decorators to make them more useful;<\/li>\n<li>handle the multiple usage patterns that decorators need to handle, inspired by the way the standard library does it;<\/li>\n<li>see that, sometimes, classes can also be used as decorators; and<\/li>\n<li>learn that classes can also be decorated.<\/li>\n<\/ul><!--v--><div class=\"notices blue\">\n<p>You can get all the Pydon'ts as a <a href=\"\/books\/pydonts\">free ebook with over +400 pages and hundreds of tips<\/a>. <a href=\"\/books\/pydonts\">Download the ebook &ldquo;Pydon'ts &ndash; write elegant Python code&rdquo; here<\/a>.<\/p>\n<\/div>\n<!--^-->\n<h2 id=\"a-function-that-did-too-much\">A function that did too much<a href=\"#a-function-that-did-too-much\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>The decorator pattern is a pattern that lets you complement a function with behaviour that is useful but that is orthogonal to the original objective of the function.\nThis pattern is relevant because you do not want to <a href=\"\/blog\/pydonts\/functions-a-complete-reference#what-goes-into-a-function-and-what-doesnt\">overcrowd your functions<\/a>, and at the same time it allows you to define this useful behaviour in a way that is reusable by other functions.<\/p>\n<p>As an example, consider how you might have implemented the mathematical operation factorial before it was introduced in the module <code>math<\/code>:<\/p>\n<pre><code class=\"language-py\"># In modern Python: from math import factorial\ndef factorial(n):\n    r = 1\n    while n &gt; 1:\n        r *= n\n        n -= 1\n    return r<\/code><\/pre>\n<p>If you are calling this function a lot with a few large integers as arguments, you may want to cache the results you compute.\nFor this effect, you may want to use a dictionary that maps inputs to outputs:<\/p>\n<pre><code class=\"language-py\">_factorial_cache = {}\n\ndef factorial(n):\n    if n not in _factorial_cache:\n        _n = n\n        r = 1\n        while _n &gt; 1:\n            r *= _n\n            _n -= 1\n        _factorial_cache[n] = r\n\n    return _factorial_cache[n]<\/code><\/pre>\n<p>This solution is far from ideal, since you introduced a function cache that is only loosely coupled to the function it's relevant for, while also introducing code in the function that is not really relevant for the original objective of the function.<\/p>\n<p>Instead of baking caching into the function, which is a poor one-time solution for something I might want to do with several functions, I can write a higher-order function that adds caching to any function I want.\nLet me walk you through this transformation.<\/p>\n<h2 id=\"factoring-out-the-orthogonal-behaviour\">Factoring out the orthogonal behaviour<a href=\"#factoring-out-the-orthogonal-behaviour\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>Instead of slapping...<\/p>","summary":"This article teaches the decorator pattern in Python, why it exists, how to use it, and when to use it to write efficient and idiomatic Python code.","date_modified":"2025-11-14T12:33:53+01:00","tags":["fp","programming","python"],"image":"\/user\/pages\/02.blog\/02.pydonts\/decorators\/thumbnail.webp"},{"title":"functools.partial","date_published":"2024-01-03T00:00:00+01:00","id":"https:\/\/mathspp.com\/blog\/functools-partial","url":"https:\/\/mathspp.com\/blog\/functools-partial","content_html":"<p>This article teaches you how to use <code>functools.partial<\/code>, how it works, and when to use it, with clear examples.<\/p>\n\n<h2 id=\"what-is-functools-partial\">What is <code>functools.partial<\/code>?<a href=\"#what-is-functools-partial\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p><code>functools.partial<\/code> is a tool from the standard module <code>functools<\/code> that allows you to curry positional and keyword arguments in functions.\nIn a certain way, it's as if <code>partial<\/code> creates a specialised version of the function you pass it in, with certain arguments frozen.<\/p>\n<p>For example, the built-in <code>int<\/code> converts objects to integers:<\/p>\n<pre><code class=\"language-pycon\">&gt;&gt;&gt; int(\"14\")\n14\n&gt;&gt;&gt; int(14.5)\n14<\/code><\/pre>\n<p>Maybe you didn't know that the built-in <code>int<\/code> also accepts a second argument that specifies the base from which the number must be converted:<\/p>\n<pre><code class=\"language-pycon\">&gt;&gt;&gt; bin(99)  # 99 in binary is 1100011\n'0b1100011'\n&gt;&gt;&gt; int(\"1100011\", base=2)\n99\n\n&gt;&gt;&gt; hex(99)  # 99 in hexadecimal is 63\n'0x63'\n&gt;&gt;&gt; int(\"63\", base=16)\n99<\/code><\/pre>\n<p>By using <code>functools.partial<\/code>, you can create specialised versions of <code>int<\/code> where the parameter <code>base<\/code> was fixed to a certain base:<\/p>\n<pre><code class=\"language-pycon\"># `partial` lives inside the module `functools`:\n&gt;&gt;&gt; from functools import partial\n\n&gt;&gt;&gt; from_bin = partial(int, base=2)\n&gt;&gt;&gt; from_bin(\"1100011\")\n99\n\n&gt;&gt;&gt; from_hex = partial(int, base=16)\n&gt;&gt;&gt; from_hex(\"63\")\n99<\/code><\/pre>\n<p>The two examples above show that the first argument to <code>partial<\/code> is the function whose argument(s) we want to freeze.\nThen, we can provide as many positional or keyword arguments as needed.\nIn our case, we just specified the parameter <code>base<\/code> as a keyword parameter.\nHere's how you could read both examples of <code>partial<\/code>:<\/p>\n<ul><li><code>partial(int, base=2)<\/code> - create a new version of <code>int<\/code> where the parameter <code>base<\/code> is always set to <code>2<\/code>; and<\/li>\n<li><code>partial(int, base=16)<\/code> &ndash; create a new version of <code>int<\/code> where the parameter <code>base<\/code> is always set to <code>16<\/code>.<\/li>\n<\/ul><h2 id=\"how-to-use-functools-partial\">How to use <code>functools.partial<\/code><a href=\"#how-to-use-functools-partial\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>The example above showed briefly how <code>partial<\/code> works and this section will go over the most important details.\nFor demonstration purposes, let us create a function with a couple of parameters:<\/p>\n<pre><code class=\"language-py\">def foo(a, b, *, c, d=10):\n    print(a, b, c, d)<\/code><\/pre>\n<p>The function <code>foo<\/code> above has 4 parameters, of which <code>c<\/code> and <code>d<\/code> are keyword-only and <code>d<\/code> has a default value of <code>10<\/code>.<\/p>\n<h3 id=\"functools-partial-and-positional-arguments\"><code>functools.partial<\/code> and positional arguments<a href=\"#functools-partial-and-positional-arguments\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h3>\n<p><code>partial<\/code> can be given positional parameters, which will be passed in, in order, to the function that is the first argument to <code>partial<\/code>.\nWhen you call the new function, the other positional arguments you pass in are appended to the ones you already specified.\nSo, <code>bar = partial(foo, 1)<\/code> is a function that has 3 parameters and that corresponds to <code>foo(1, b, *, c, d=10)<\/code>.\nSimilarly, <code>baz = partial(foo, 1, 2)<\/code> is a function that has 2 parameters and that corresponds to <code>foo(1, 2, *, c, d=10)<\/code>.<\/p>\n<pre><code class=\"language-pycon\">&gt;&gt;&gt; bar = partial(foo, 1)\n&gt;&gt;&gt; bar(20, c=30, d=40)\n1 20 30 40\n\n&gt;&gt;&gt; baz = partial(foo, 1, 2)\n&gt;&gt;&gt; baz(c=30, d=40)\n1 2 30 40<\/code><\/pre>\n<p>Notice that <code>partial<\/code> doesn't do any type of validation whatsoever regarding the number of arguments you pass in.\nThis means that a call to <code>partial<\/code> might succeed but then produce a function that is unusable.<\/p>\n<p>The example...<\/p>","summary":"This article teaches you how to use `functools.partial`, how it works, and when to use it, with clear examples.","date_modified":"2026-01-28T20:06:35+01:00","tags":["fp","modules","programming","python"],"image":"\/user\/pages\/02.blog\/functools-partial\/thumbnail.webp"},{"title":"The power of reduce | Pydon&#039;t \ud83d\udc0d","date_published":"2021-06-08T00:00:00+02:00","id":"https:\/\/mathspp.com\/blog\/pydonts\/the-power-of-reduce","url":"https:\/\/mathspp.com\/blog\/pydonts\/the-power-of-reduce","content_html":"<p>In this Pydon't we will take a look at the <code>reduce<\/code> function,\nwhich used to be a built-in function and is currently\nin the <code>functools<\/code> module.<\/p>\n\n<p><img alt=\"A Python code snippet that uses short-circuiting.\" src=\"\/user\/pages\/02.blog\/02.pydonts\/the-power-of-reduce\/thumbnail.svg?decoding=auto&amp;fetchpriority=auto\"><\/p>\n<p>(If you are new here and have no idea what a Pydon't is, you may want to read the\n<a href=\"\/blog\/pydonts\/pydont-manifesto\">Pydon't Manifesto<\/a>.)<\/p>\n<h2 id=\"introduction\">Introduction<a href=\"#introduction\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>In this Pydon't I'll talk about <code>reduce<\/code>, a function that used\nto be a built-in function and that was moved to the <code>functools<\/code>\nmodule with Python 3.<\/p>\n<p>Throughout all of the Pydon'ts I have been focusing only\non Python features that you can use without having to import\nanything, so in that regard this Pydon't will be a little bit different.<\/p>\n<p>In this Pydon't, you will:<\/p>\n<ul><li>see how <code>reduce<\/code> works;<\/li>\n<li>learn about the relationship between <code>reduce<\/code> and <code>for<\/code> loops;<\/li>\n<li>notice that <code>reduce<\/code> hides in a handful of other built-in functions we all know and love;<\/li>\n<li>learn about a neat use-case for <code>reduce<\/code>;<\/li>\n<\/ul><!--v--><div class=\"notices blue\">\n<p>You can get all the Pydon'ts as a <a href=\"\/books\/pydonts\">free ebook with over +400 pages and hundreds of tips<\/a>. <a href=\"\/books\/pydonts\">Download the ebook &ldquo;Pydon'ts &ndash; write elegant Python code&rdquo; here<\/a>.<\/p>\n<\/div>\n<!--^-->\n<h2 id=\"how-reduce-works\">How <code>reduce<\/code> works<a href=\"#how-reduce-works\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p><code>reduce<\/code> is a tool that is typically associated with functional programming,\nwhich is a programming paradigm that I feel sometimes is underappreciated.\nIn a short sentence, <code>reduce<\/code> takes an iterable and a binary function\n(a function that takes two arguments),\nand then uses that binary function to boil the iterable down to a single value.<\/p>\n<p>This might sound weird or complicated, so the best thing I can do is to show\nyou a simplified implementation of reduce:<\/p>\n<pre><code class=\"language-py\">def reduce(function, iterable, initial_value):\n    result = initial_value\n    for value in iterable:\n        result = function(result, value)\n    return result<\/code><\/pre>\n<p>If you look at it, there really isn't much going on inside that <code>for<\/code> loop:\nwe just keep updating the <code>result<\/code> variable with the argument <code>function<\/code>\nand the consecutive values in the <code>iterable<\/code> argument.<\/p>\n<p>But I can make this even easier to understand for you.\nAnd, in order to do that, I just have to point out a bunch of <code>reduce<\/code>\nuse cases that you use all the time!\nPerhaps the simplest one, and the one that shows up more often, is the <code>sum<\/code> built-in:<\/p>\n<pre><code class=\"language-py\">&gt;&gt;&gt; sum(range(10))\n45\n&gt;&gt;&gt; from functools import reduce; import operator\n&gt;&gt;&gt; reduce(operator.add, range(10))\n45<\/code><\/pre>\n<p>The <code>operator.add<\/code> there is just a way to programmatically refer to the built-in\naddition with <code>+<\/code> in Python.<\/p>\n<p>From the <a href=\"https:\/\/docs.python.org\/3\/library\/operator.html\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" class=\"external-link no-image\">documentation on <code>operator<\/code><\/a>,<\/p>\n<blockquote>\n<p>&ldquo;The <code>operator<\/code> module exports a set of efficient functions corresponding to the\nintrinsic operators of Python.\nFor example, <code>operator.add(x, y)<\/code> is equivalent to the expression <code>x+y<\/code>.&rdquo;<\/p>\n<\/blockquote>\n<p>You probably have seen <code>sum<\/code> before, right?\nIt just adds up all the elements in an iterable.\nThat's basically what <code>reduce<\/code> does, if the function we give it is the addition.\nTo make the connection clearer, let's implement our own <code>sum<\/code> function:<\/p>\n<pre><code class=\"language-py\">def sum(iterable):\n    acc = 0\n    for elem in iterable:\n        acc += elem\n    return acc<\/code><\/pre>\n<p>Are you comfortable with the implementation above?\nNow let me rejig it a little...<\/p>","summary":"In this Pydon&#039;t we will take a look at the `reduce` function, which used to be a built-in function and is currently in the `functools` module.","date_modified":"2025-07-23T16:49:02+02:00","tags":["fp","programming","python"],"image":"\/user\/pages\/02.blog\/02.pydonts\/the-power-of-reduce\/thumbnail.webp"}]}
