{"course":{"slug":"python-for-ai","title":"Python, from Zero, for AI","url":"https://addaly.com/learn/python-for-ai","level":"beginner","track":"build"},"lesson":{"slug":"pure-functions","title":"Side effects, and why some functions are easy to test","url":"https://addaly.com/learn/python-for-ai/pure-functions","position":28,"of":89,"minutes":8,"answer":"Functions that read the clock, the network or a model are impure, so pass those dependencies in as arguments and keep the parsing, calculation and formatting pure enough to test for free.","keyIdea":"Functions that read the clock, the network or a model are impure, so pass those dependencies in as arguments and keep the parsing, calculation and formatting pure enough to test for free."},"body":{"format":"markdown","text":"## Two kinds of function\n\n```python\ndef with_tax(amount, rate=0.18):\n    return round(amount * (1 + rate), 2)\n```\n\nGiven the same arguments, this returns the same answer every time, and calling it changes nothing anywhere else. That is a **pure** function.\n\n```python\ndef save_invoice(invoice):\n    with open(\"invoices.csv\", \"a\") as f:\n        f.write(invoice.as_row())\n    logger.info(\"saved\")\n```\n\nThis one has **side effects**: it touches a file and a log. Call it twice and the world is different than if you called it once.\n\nBoth kinds are necessary. A program of only pure functions cannot read input or show output, so it does nothing observable. The point is not to eliminate side effects; it is to know which functions have them.\n\n## What counts as a side effect\n\n- Reading or writing a file, a database, a network\n- Printing, or logging\n- Changing a global, or a module-level cache\n- **Mutating an argument**, the quiet one\n- Reading the clock, or a random number, or an environment variable\n\nThat last group makes a function impure without changing anything, because the result depends on something other than its arguments. `def is_expired(date): return date < datetime.now()` cannot be tested for a fixed answer, and the test that passes today fails next year.\n\nThe fix is to pass the dependency in:\n\n```python\ndef is_expired(date, now):\n    return date < now\n```\n\nNow the test is one line, the production call is `is_expired(d, datetime.now())`, and the impurity has moved to the caller where it is visible. The same trick handles randomness (pass a seeded generator) and configuration.\n\n## Why this matters more with AI in the picture\n\nA call to a language model is impure in the strongest way: same input, different output, at a cost, over a network that can fail. Mix it into a function that also parses, validates and formats, and you have code that cannot be tested without spending money and cannot be debugged because you can never reproduce the run.\n\nThe shape that works:\n\n```python\ndef build_prompt(question, context):        # pure\n    ...\n\ndef parse_reply(text):                      # pure\n    ...\n\ndef answer(question, context, call_model):  # impure only in the argument\n    reply = call_model(build_prompt(question, context))\n    return parse_reply(reply)\n```\n\n`build_prompt` and `parse_reply` get tested exhaustively for nothing. `answer` gets tested with a fake `call_model` that returns a fixed string. The real model appears once, at the edge of the program. Module four returns to this when it covers testing code that calls an API.\n\n## Mutating what you were given\n\n```python\ndef normalise(rows):\n    for r in rows:\n        r[\"name\"] = r[\"name\"].strip().title()\n    return rows\n```\n\nThis looks pure (it takes rows and returns rows) and it has quietly rewritten the caller's data. Every later use of the original now sees the modified version, including code that wanted the raw values.\n\nTwo honest designs:\n\n```python\ndef normalised(rows):                       # returns new, leaves input alone\n    return [{**r, \"name\": r[\"name\"].strip().title()} for r in rows]\n\ndef normalise_in_place(rows) -> None:       # mutates, returns nothing\n    for r in rows:\n        r[\"name\"] = r[\"name\"].strip().title()\n```\n\nName and return type together tell the caller which one they have. The version that mutates *and* returns is the one that causes trouble, because it invites `clean = normalise(rows)` and the reader assumes `rows` is untouched.\n\n## A shape for whole programs\n\nThe pattern that scales is a **pure core with an effectful shell**:\n\n- The outer layer reads arguments, files and network responses.\n- The middle is pure: parsing, calculation, formatting, decisions.\n- The outer layer writes the results.\n\nMost of the interesting logic ends up in the middle, where it is testable without a database, a network or a clock. When a program is hard to test, it is nearly always because a decision is buried inside a function that is also doing I/O.\n\n## Where purity is a false economy\n\nDo not thread a database connection through nine layers of arguments to keep a function pure. Do not rebuild a large list on every call to avoid mutation when the profiler shows it costs a second. Purity is a tool for testability and reasoning, not a rule to be satisfied. The realistic goal is that every function has a side effect you could name in a sentence, or none at all, and that you know which."},"check":{"question":"A summariser is one function that reads a file, calls a language model, parses the reply and writes a report. It fails intermittently in production and cannot be reproduced. Which change most improves the situation?","options":[{"text":"Add retries around the whole function so intermittent failures resolve themselves.","correct":false,"tempting":"Hides variability rather than isolating it, and retrying a function with file writes in it can duplicate output."},{"text":"Cache the model's replies to disk so the same input always produces the same output.","correct":false,"tempting":"Makes reruns cheaper and does help reproduce one incident, but leaves the parsing and decision logic untestable without the cache."},{"text":"Split out the prompt building and reply parsing as pure functions and pass the model call in, so those parts can be tested against a fixed reply.","correct":true},{"text":"Convert the function to read its input from a variable rather than a file, removing one side effect.","correct":false,"tempting":"Removes the least troublesome effect while the non-determinism from the model and the untestable parsing both remain."}]},"prev":{"slug":"project-layout","title":"Laying out a project so the imports keep working","url":"https://addaly.com/learn/python-for-ai/project-layout"},"next":{"slug":"command-line-arguments","title":"Giving your script a proper command line","url":"https://addaly.com/learn/python-for-ai/command-line-arguments"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'Side effects, and why some functions are easy to test', in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/pure-functions (Accessed: 29 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Side effects, and why some functions are easy to test","courseTitle":"Python, from Zero, for AI","module":{"index":3,"slug":"functions-and-structure","title":"Functions, modules, and code you can read again in March"},"answer":null,"keyIdea":"Functions that read the clock, the network or a model are impure, so pass those dependencies in as arguments and keep the parsing, calculation and formatting pure enough to test for free.","hero":{"kind":"plate","image":null,"alt":null,"caption":null},"blocks":[{"t":"h2","id":"two-kinds-of-function","runs":[{"text":"Two kinds of function"}]},{"t":"code","lang":"python","label":"Python","text":"def with_tax(amount, rate=0.18):\n    return round(amount * (1 + rate), 2)"},{"t":"p","runs":[{"text":"Given the same arguments, this returns the same answer every time, and calling it changes nothing anywhere else. That is a "},{"text":"pure","b":true},{"text":" function."}]},{"t":"code","lang":"python","label":"Python","text":"def save_invoice(invoice):\n    with open(\"invoices.csv\", \"a\") as f:\n        f.write(invoice.as_row())\n    logger.info(\"saved\")"},{"t":"p","runs":[{"text":"This one has "},{"text":"side effects","b":true},{"text":": it touches a file and a log. Call it twice and the world is different than if you called it once."}]},{"t":"p","runs":[{"text":"Both kinds are necessary. A program of only pure functions cannot read input or show output, so it does nothing observable. The point is not to eliminate side effects; it is to know which functions have them."}]},{"t":"h2","id":"what-counts-as-a-side-effect","runs":[{"text":"What counts as a side effect"}]},{"t":"ul","items":[[{"text":"Reading or writing a file, a database, a network"}],[{"text":"Printing, or logging"}],[{"text":"Changing a global, or a module-level cache"}],[{"text":"Mutating an argument","b":true},{"text":", the quiet one"}],[{"text":"Reading the clock, or a random number, or an environment variable"}]]},{"t":"p","runs":[{"text":"That last group makes a function impure without changing anything, because the result depends on something other than its arguments. "},{"text":"def is_expired(date): return date < datetime.now()","code":true},{"text":" cannot be tested for a fixed answer, and the test that passes today fails next year."}]},{"t":"p","runs":[{"text":"The fix is to pass the dependency in:"}]},{"t":"code","lang":"python","label":"Python","text":"def is_expired(date, now):\n    return date < now"},{"t":"p","runs":[{"text":"Now the test is one line, the production call is "},{"text":"is_expired(d, datetime.now())","code":true},{"text":", and the impurity has moved to the caller where it is visible. The same trick handles randomness (pass a seeded generator) and configuration."}]},{"t":"h2","id":"why-this-matters-more-with-ai-in-the-picture","runs":[{"text":"Why this matters more with AI in the picture"}]},{"t":"p","runs":[{"text":"A call to a language model is impure in the strongest way: same input, different output, at a cost, over a network that can fail. Mix it into a function that also parses, validates and formats, and you have code that cannot be tested without spending money and cannot be debugged because you can never reproduce the run."}]},{"t":"p","runs":[{"text":"The shape that works:"}]},{"t":"code","lang":"python","label":"Python","text":"def build_prompt(question, context):        # pure\n    ...\n\ndef parse_reply(text):                      # pure\n    ...\n\ndef answer(question, context, call_model):  # impure only in the argument\n    reply = call_model(build_prompt(question, context))\n    return parse_reply(reply)"},{"t":"p","runs":[{"text":"build_prompt","code":true},{"text":" and "},{"text":"parse_reply","code":true},{"text":" get tested exhaustively for nothing. "},{"text":"answer","code":true},{"text":" gets tested with a fake "},{"text":"call_model","code":true},{"text":" that returns a fixed string. The real model appears once, at the edge of the program. Module four returns to this when it covers testing code that calls an API."}]},{"t":"h2","id":"mutating-what-you-were-given","runs":[{"text":"Mutating what you were given"}]},{"t":"code","lang":"python","label":"Python","text":"def normalise(rows):\n    for r in rows:\n        r[\"name\"] = r[\"name\"].strip().title()\n    return rows"},{"t":"p","runs":[{"text":"This looks pure (it takes rows and returns rows) and it has quietly rewritten the caller’s data. Every later use of the original now sees the modified version, including code that wanted the raw values."}]},{"t":"p","runs":[{"text":"Two honest designs:"}]},{"t":"code","lang":"python","label":"Python","text":"def normalised(rows):                       # returns new, leaves input alone\n    return [{**r, \"name\": r[\"name\"].strip().title()} for r in rows]\n\ndef normalise_in_place(rows) -> None:       # mutates, returns nothing\n    for r in rows:\n        r[\"name\"] = r[\"name\"].strip().title()"},{"t":"p","runs":[{"text":"Name and return type together tell the caller which one they have. The version that mutates "},{"text":"and","i":true},{"text":" returns is the one that causes trouble, because it invites "},{"text":"clean = normalise(rows)","code":true},{"text":" and the reader assumes "},{"text":"rows","code":true},{"text":" is untouched."}]},{"t":"h2","id":"a-shape-for-whole-programs","runs":[{"text":"A shape for whole programs"}]},{"t":"p","runs":[{"text":"The pattern that scales is a "},{"text":"pure core with an effectful shell","b":true},{"text":":"}]},{"t":"ul","items":[[{"text":"The outer layer reads arguments, files and network responses."}],[{"text":"The middle is pure: parsing, calculation, formatting, decisions."}],[{"text":"The outer layer writes the results."}]]},{"t":"p","runs":[{"text":"Most of the interesting logic ends up in the middle, where it is testable without a database, a network or a clock. When a program is hard to test, it is nearly always because a decision is buried inside a function that is also doing I/O."}]},{"t":"h2","id":"where-purity-is-a-false-economy","runs":[{"text":"Where purity is a false economy"}]},{"t":"p","runs":[{"text":"Do not thread a database connection through nine layers of arguments to keep a function pure. Do not rebuild a large list on every call to avoid mutation when the profiler shows it costs a second. Purity is a tool for testability and reasoning, not a rule to be satisfied. The realistic goal is that every function has a side effect you could name in a sentence, or none at all, and that you know which."}]}],"check":{"question":[{"text":"A summariser is one function that reads a file, calls a language model, parses the reply and writes a report. It fails intermittently in production and cannot be reproduced. Which change most improves the situation?"}],"options":[{"text":[{"text":"Add retries around the whole function so intermittent failures resolve themselves."}],"correct":false,"tempting":[{"text":"Hides variability rather than isolating it, and retrying a function with file writes in it can duplicate output."}]},{"text":[{"text":"Cache the model’s replies to disk so the same input always produces the same output."}],"correct":false,"tempting":[{"text":"Makes reruns cheaper and does help reproduce one incident, but leaves the parsing and decision logic untestable without the cache."}]},{"text":[{"text":"Split out the prompt building and reply parsing as pure functions and pass the model call in, so those parts can be tested against a fixed reply."}],"correct":true,"tempting":null},{"text":[{"text":"Convert the function to read its input from a variable rather than a file, removing one side effect."}],"correct":false,"tempting":[{"text":"Removes the least troublesome effect while the non-determinism from the model and the untestable parsing both remain."}]}],"order":[0,3,1,2],"why":null},"prev":{"slug":"project-layout","title":"Laying out a project so the imports keep working","minutes":8},"next":{"slug":"command-line-arguments","title":"Giving your script a proper command line","minutes":8}}}