ArjanCodes Functional Core Python Design

Refactor any messy Python function into a clean, testable pipeline by separating pure calculations from side effects using functional programming principles.

// TL;DR

ArjanCodes Functional Core Python Design is a refactoring framework that transforms messy, hard-to-test Python functions into clean pipelines by separating pure calculations from side effects. You extract rules into pure functions, model data flow as a transformation pipeline using immutable dataclasses, keep all decision logic in a functional core, and wrap it in a thin imperative shell that handles databases, APIs, and I/O. Use it whenever a Python function does too many things at once — mixing calculations, state mutation, external calls, and decisions — or when a function is hard to read, hard to test, or keeps growing as new rules get added.

// When should you use ArjanCodes Functional Core Python Design?

Use this skill whenever you encounter a Python function that does too many things at once — mixing calculations, state mutation, database calls, and decision-making. Trigger it when a function is hard to read, hard to test, or keeps growing as new rules get added.

// What do you need before refactoring a function into a functional core?

  • target_function_or_modulerequired
    The Python function, class, or module you want to refactor. Paste the code or describe what it does.
  • domain_contextrequired
    What problem domain is this code in? (e.g. fraud detection, billing, data processing). Helps name the transformation stages correctly.
  • external_dependencies
    List any external systems the code currently touches: databases, APIs, ML models, file systems, notification services, etc.

// What principles guide Functional Core Python design?

Pure Functions

A pure function always returns the same output for the same input, and changes nothing outside itself. It reads data passed in as arguments, computes something, and returns a result — no silent fetching from elsewhere, no mutation of its inputs.

Explicit Dependencies

If a calculation needs something, pass it in as an argument instead of letting it quietly fetch it from somewhere else in the code. This makes dependencies visible and the function independently understandable.

Transformation Pipeline

Model all changes to data as a series of transformations: data comes in, a transformation is applied, new data comes out. The output of one function becomes the input of the next. Never mutate the same object in place through multiple stages.

Immutable Data Structures

Use immutable objects (e.g. frozen dataclasses, tuples instead of lists) to represent intermediate and final values in the pipeline. This prevents any step from secretly changing data that another step depends on, and makes program flow obvious.

Functional Core, Imperative Shell

The decision-making logic lives in a pure functional core that knows nothing about databases, APIs, or external systems. A thin imperative shell wraps the core, handling all interaction with the outside world. You only need integration tests for the shell; the core is testable with plain function calls and simple values.

Separation of What from Where

The core logic must not know where data came from or where decisions will be stored. Keep fraud logic (or any domain logic) ignorant of its infrastructure so it stays pure and stable as infrastructure changes.

// How do you refactor a Python function into a functional core step by step?

  1. 1

    Audit the target function for mixed concerns

    List every distinct thing the function does. Categorise each into one of: (a) calculation/rule, (b) state mutation, (c) external I/O (DB, API, file), (d) decision-making. Any function doing more than one category is a refactor candidate.

  2. 2

    Extract pure calculation functions

    Pull each calculation or rule out into its own named function. Each extracted function must: take only what it needs as arguments, return a value, and touch no external state. Ask: 'If I call this with the same inputs twice, do I always get the same output?' If yes, it qualifies as a pure function.

  3. 3

    Design the transformation pipeline stages

    Name the logical stages data passes through (e.g. raw input → features → risk assessment → decision). Each stage should map to a clearly named data type. The number of stages equals the number of meaningful transformations in your domain — do not force arbitrary splits.

  4. 4

    Define immutable data classes for each stage's output

    Create frozen dataclasses (or named tuples) for each intermediate and final value in the pipeline. Use tuples instead of lists for any collection inside these objects. Each class should represent one stable snapshot of data — not an object that gets mutated as processing continues.

  5. 5

    Implement one pure function per pipeline stage

    Write a function for each transformation: it takes the previous stage's immutable output (plus any needed pure inputs) and returns the next stage's immutable output. No DB calls, no API calls, no logging inside these functions. If a stage needs external data (e.g. a model prediction), pass that data in as an argument — do not fetch it inside the function.

  6. 6

    Compose the pipeline in an orchestrator function

    Write a top-level function that calls each stage function in sequence, passing outputs as inputs. Use intermediate variables for readability and debuggability — this is preferred in Python over deeply nested composition or compose operators, which are more idiomatic in languages like Haskell.

  7. 7

    Build the Imperative Shell around the functional core

    Create a service or handler layer (the imperative shell) that: retrieves raw data from external sources, prepares any external inputs the core needs (e.g. model predictions, config values), calls the orchestrator function, and persists or dispatches the result. The shell is allowed to be imperative — that is intentional. The core must remain ignorant of the shell.

  8. 8

    Validate testability of the core

    Confirm that every function in the functional core can be tested with plain function calls and simple values — no mocking of databases, notification systems, or APIs required. If you need to mock something to test a core function, it has leaked an external dependency and must be refactored.

// What does functional core refactoring look like in real Python code?

An e-commerce order processing function that validates stock, applies discount rules, charges the customer, updates inventory, and sends a confirmation email — all in one place.

Extract discount calculation and eligibility checks into pure functions (e.g. calculate_discount(cart, customer_tier) → float). Design a pipeline: raw order → validated order features → pricing assessment → order decision. Use frozen dataclasses for PricingAssessment and OrderDecision. Write an imperative shell (OrderService) that fetches stock levels and customer data, passes them into the pure core, then handles payment charging, inventory mutation, and email dispatch.

A data pipeline function that fetches records from an API, applies several cleaning rules, scores each record for quality, flags bad ones, and writes results to a database.

Pull each cleaning rule into its own pure function returning a score or boolean. Model the pipeline as: raw record → extracted features → quality assessment → disposition decision. Use frozen dataclasses for QualityAssessment and Disposition. The imperative shell handles API fetching and DB writes; the core functions receive already-fetched data and return immutable results the shell can then persist.

// What mistakes should you avoid when applying functional core design?

  • Mutating the same object across multiple processing steps — this means you need to understand an object's entire history to understand its current state, and it may be in an invalid intermediate state.
  • Mixing external I/O (database saves, API calls, logging) inside core calculation functions — this destroys testability and violates the Functional Core, Imperative Shell separation.
  • Forcing complete immutability everywhere regardless of cost — if you are constantly copying huge data structures just to stay pure, that is not a good trade-off in Python. Use immutability where it makes the flow easier to reason about.
  • Silently fetching dependencies inside a function instead of passing them as arguments — this hides what a function actually depends on and breaks the explicit dependencies principle.
  • Using deeply nested function composition syntax in Python for the sake of looking functional — explicit intermediate variables are more readable and debuggable in Python and produce the same design.
  • Assuming AI-generated code embodies good design decisions — if you do not understand these principles yourself, you cannot judge or guide what your AI coding tool produces.

// What are the key terms in Functional Core Python design?

Pure Function
A function that always returns the same output for the same input, and changes nothing outside itself. It has no side effects and makes all its dependencies explicit through its arguments.
Functional Core, Imperative Shell
An architectural pattern where all decision-making logic lives in a pure functional core (testable with simple values, ignorant of infrastructure), wrapped by a thin imperative shell that handles all interaction with external systems (databases, APIs, files).
Transformation Pipeline
A design structure where data flows through a sequence of named stages, each stage taking the previous stage's output as its input and producing a new immutable value. Models program flow as: data in → transformation → data out.
Immutable Data Structures
Data objects that cannot be changed after creation, implemented in Python as frozen dataclasses or named tuples. Used to represent each stage's output in a transformation pipeline, preventing hidden mutation.
Imperative Shell
The outer layer of a system that handles all interaction with the outside world: fetching data from databases, calling APIs, loading models, writing results, sending alerts. It calls into the functional core and handles the results.
Side Effects
Any action a function takes that affects the world outside itself — saving to a database, sending a notification, mutating an argument. The goal is not to eliminate side effects but to isolate them clearly in the imperative shell.
Explicit Dependencies
The practice of passing everything a function needs as arguments rather than having it fetch or reference external state. Makes dependencies visible and functions independently understandable.

// FREQUENTLY ASKED QUESTIONS

What is the Functional Core, Imperative Shell pattern in Python?

It's an architectural pattern where all decision-making and calculation logic lives in a pure functional core that knows nothing about databases, APIs, or files, wrapped by a thin imperative shell that handles every interaction with the outside world. The core is testable with plain function calls and simple values; only the shell needs integration tests.

What is a pure function in Python?

A pure function always returns the same output for the same input and changes nothing outside itself. It reads data passed in as arguments, computes a result, and returns it — no silent fetching from a database, no mutation of its inputs, no side effects like logging or API calls. This makes it independently understandable and trivially testable.

How do I refactor a Python function that does too many things?

Audit the function and categorize each thing it does as a calculation, state mutation, external I/O, or decision. Extract calculations into pure functions that take arguments and return values. Model the data flow as a transformation pipeline using immutable dataclasses, then move all database, API, and file operations into an imperative shell that calls the pure core.

How do I make my Python code more testable without mocking databases?

Move all database, API, and I/O calls out of your logic and into an imperative shell, keeping your decision-making in a pure functional core. Core functions receive already-fetched data as arguments and return immutable results, so you test them with plain values. If you need to mock a database to test core logic, a dependency has leaked and must be extracted.

When should I use the Functional Core, Imperative Shell pattern?

Use it whenever a Python function mixes calculations, state mutation, database calls, and decision-making in one place, or whenever a function is hard to read, hard to test, or keeps growing as new rules get added. It's especially valuable for domain logic like fraud detection, billing, pricing, and data processing where rules change but infrastructure should stay separate.

How does functional core design compare to a generic class-based refactor?

A generic class-based refactor often still hides database calls and state mutation inside methods, so you still need heavy mocking to test. Functional core design forces dependencies to be explicit arguments and isolates all side effects in the shell, so your business logic becomes pure, immutable, and testable with simple values — making program flow far easier to reason about.

What results can I expect after applying this refactoring?

You get business logic you can test without mocking databases or APIs, functions that are independently understandable because their dependencies are explicit, and data flow you can trace stage by stage through immutable snapshots. Adding new rules becomes a matter of extending the pipeline rather than growing a tangled function, and infrastructure changes no longer ripple into your core logic.

What is a transformation pipeline in functional Python design?

A transformation pipeline models all changes to data as a sequence of named stages, where each stage takes the previous stage's immutable output as input and produces a new immutable value. For example: raw input → features → risk assessment → decision. Nothing is mutated in place — each stage is a stable snapshot, making the program flow obvious and debuggable.

Do I have to make everything immutable in Python to use this?

No — forcing complete immutability everywhere regardless of cost is a pitfall. If you're constantly copying huge data structures just to stay pure, that's a bad trade-off in Python. Use immutable frozen dataclasses and tuples where they make the pipeline easier to reason about, and don't sacrifice performance for purity where it doesn't add clarity.

How do I decide how many stages my pipeline should have?

The number of stages equals the number of meaningful transformations in your domain — do not force arbitrary splits. Name the logical stages data actually passes through, such as raw record → extracted features → quality assessment → disposition. Each stage should map to a clearly named immutable data type representing one stable snapshot of the data.

// GET THIS SKILL — FREE

Use this skill in your AI

Every skill on SkillForge is free. Drop your email and copy this skill straight into Claude, ChatGPT, or any LLM.

We'll email you when new skills drop. Unsubscribe anytime.