Functional Weave
Code in Python

health.qrisk-inputs-validate

Check a QRISK3 cardiovascular risk input set against the calculator's published ranges; does not compute risk.

1.0.0 (not the latest) · published 2026-10-03 by charlie · Anterra

Pinned by 29 tests, run in TypeScript, Python and Rust.

Not professional advice. This capability calculates health figures from published rules. It is a software component for developers, not medical advice. Rules change and every rate here has an effective date. Check that the dates cover your case. Verify results against the official sources listed in its README, and have a primary-care clinician review how you use it, before anyone relies on the output. Provided “as is” under its licence, without warranty.

Not a medical device. It is not intended to diagnose, treat or support clinical decisions about any individual. Anyone building it into clinical software is responsible for that software’s regulatory status, and must validate it under their own clinical governance.

What it does

Status: needs review and sign-off by a qualified clinician before it is published. Not a medical device; for decision support only; always follow local clinical guidelines.

Checks that a set of inputs is fit to be given to the QRISK3 cardiovascular risk calculator. **It does NOT compute risk.** QRISK3 itself is a licensed algorithm (ClinRisk / Endeavour Predict); use an accredited implementation for the score. This capability catches the data problems before the call: missing required values, values outside the ranges the calculator accepts, a height without a weight, and people QRISK3 is not valid for.

For example

  • validate_qrisk_inputs(age 64, sex male, ethnicity indian, postcode SW1A 1AA, smoking ex-smoker, diabetes type-2, family history cvd true, chronic kidney disease false, atrial fibrillation false, blood …) → valid true, errors a complete, valid input set
  • validate_qrisk_inputs(age 40, sex female, ethnicity white-or-not-stated, postcode —, smoking non-smoker, diabetes none, family history cvd false, chronic kidney disease false, atrial fibrillation false…) → valid true, errors the minimum: required fields only, every optional one null
  • validate_qrisk_inputs(age 25, sex female, ethnicity white-or-not-stated, postcode —, smoking non-smoker, diabetes none, family history cvd false, chronic kidney disease false, atrial fibrillation false…) → valid true, errors age 25 is the youngest accepted

The function

The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.

def validate_qrisk_inputs(inputs: QriskInputs) -> QriskInputsValidation
inputsQriskInputsthe values a QRISK3 calculation would be given; null where not recorded
returnsQriskInputsValidationevery problem found, in field order; valid when there are none

The types it declares, generated into your project

@dataclass(frozen=True)
class QriskInputs:
    """The QRISK3 input set, as raw recorded values to be checked."""

    #: years; required, 25 to 84
    age: Optional[int]
    #: female or male; required
    sex: Optional[str]
    #: white-or-not-stated, indian, pakistani, bangladeshi, chinese, other-asian, black-caribbean, black-african or other; required
    ethnicity: Optional[str]
    #: UK postcode; optional
    postcode: Optional[str]
    #: non-smoker, ex-smoker, light (under 10 a day), moderate (10 to 19) or heavy (20 or more); required
    smoking: Optional[str]
    #: none, type-1 or type-2; required
    diabetes: Optional[str]
    #: angina or heart attack in a 1st degree relative
    family_history_cvd: bool
    #: CKD stage 3, 4 or 5
    chronic_kidney_disease: bool
    atrial_fibrillation: bool
    #: on treatment for high blood pressure
    blood_pressure_treatment: bool
    migraine: bool
    rheumatoid_arthritis: bool
    #: systemic lupus erythematosus (SLE)
    systemic_lupus: bool
    #: schizophrenia, bipolar disorder or moderate/severe depression
    severe_mental_illness: bool
    #: on atypical antipsychotic medication
    atypical_antipsychotic: bool
    #: on regular steroid tablets
    corticosteroids: bool
    #: a diagnosis of or treatment for erectile dysfunction
    erectile_dysfunction: bool
    #: total cholesterol / HDL; optional, 1.0 to 11.0
    cholesterol_hdl_ratio: Optional[float]
    #: mmHg; optional, 70 to 210
    systolic_bp: Optional[int]
    #: standard deviation of at least two recent systolic readings; optional, 0.0 to 40.0
    systolic_bp_sd: Optional[float]
    #: whole centimetres; optional with weight, 140 to 210
    height_cm: Optional[int]
    #: whole kilograms; optional with height, 40 to 180
    weight_kg: Optional[int]
    #: already diagnosed with coronary heart disease, stroke or TIA
    existing_cvd: bool
    #: already taking a statin
    on_statins: bool

@dataclass(frozen=True)
class QriskInputError:
    """One problem with one field."""

    #: the QriskInputs field name
    field: str
    #: required, out-of-range, unknown-value, incomplete-pair, bad-postcode or not-applicable
    reason: str
    #: plain English, in the calculator's own wording where it has one
    message: str

@dataclass(frozen=True)
class QriskInputsValidation:
    """Whether the set can be given to QRISK3, and if not, why."""

    valid: bool
    #: empty when valid
    errors: List[QriskInputError]

Your code names it in one line, in the file that uses it

from fune.health.qrisk_inputs_validate import validate_qrisk_inputs  # health.qrisk-inputs-validate@^1
impl/python.py · 126 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import math
from typing import List, Optional, Sequence

from .health_qrisk_inputs_validate_types import QriskInputError, QriskInputs, QriskInputsValidation
from .validation_uk_postcode import validate_uk_postcode  ← from validation.uk-postcode ^2.0.0 · built alongside by fune

_SEXES = ("female", "male")
_ETHNICITIES = (
    "white-or-not-stated",
    "indian",
    "pakistani",
    "bangladeshi",
    "chinese",
    "other-asian",
    "black-caribbean",
    "black-african",
    "other",
)
_SMOKING = ("non-smoker", "ex-smoker", "light", "moderate", "heavy")
_DIABETES = ("none", "type-1", "type-2")


# A value of the wrong type is a programming error, not a clinical one: it
# raises rather than being reported.
def _whole_or_none(name: str, value: object) -> Optional[int]:
    if value is None:
        return None
    if isinstance(value, bool) or not (
        isinstance(value, int) or (isinstance(value, float) and math.isfinite(value) and value.is_integer())
    ):
        raise TypeError("%s must be a whole number or null, received %r" % (name, value))
    return int(value)


def _number_or_none(name: str, value: object) -> Optional[float]:
    if value is None:
        return None
    if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
        raise TypeError("%s must be a number or null, received %r" % (name, value))
    return float(value)


def _text_or_none(name: str, value: object) -> Optional[str]:
    if value is None:
        return None
    if not isinstance(value, str):
        raise TypeError("%s must be text or null, received %r" % (name, value))
    return value


def validate_qrisk_inputs(inputs: QriskInputs) -> QriskInputsValidation:
    """Check a QRISK3 input set against the calculator's published input
    definitions (qrisk.org form and its validation). It reports every problem,
    in field order, and never computes a risk."""
    errors: List[QriskInputError] = []

    def add(field: str, reason: str, message: str) -> None:
        errors.append(QriskInputError(field=field, reason=reason, message=message))

    age = _whole_or_none("age", inputs.age)
    sex = _text_or_none("sex", inputs.sex)
    ethnicity = _text_or_none("ethnicity", inputs.ethnicity)
    postcode = _text_or_none("postcode", inputs.postcode)
    smoking = _text_or_none("smoking", inputs.smoking)
    diabetes = _text_or_none("diabetes", inputs.diabetes)
    ratio = _number_or_none("cholesterolHdlRatio", inputs.cholesterol_hdl_ratio)
    sbp = _whole_or_none("systolicBp", inputs.systolic_bp)
    sbp_sd = _number_or_none("systolicBpSd", inputs.systolic_bp_sd)
    height = _whole_or_none("heightCm", inputs.height_cm)
    weight = _whole_or_none("weightKg", inputs.weight_kg)

    age_message = "Age: enter an integer between 25 and 84"
    if age is None:
        add("age", "required", age_message)
    elif age < 25 or age > 84:
        add("age", "out-of-range", age_message)

    def choice(field: str, value: Optional[str], allowed: Sequence[str], label: str) -> None:
        message = "%s: enter one of %s" % (label, ", ".join(allowed))
        if value is None:
            add(field, "required", message)
        elif value not in allowed:
            add(field, "unknown-value", message)

    choice("sex", sex, _SEXES, "Sex")
    choice("ethnicity", ethnicity, _ETHNICITIES, "Ethnicity")
    # Blank means unknown, as on the calculator ("leave blank if unknown").
    if postcode is not None and postcode.strip() != "" and not validate_uk_postcode(postcode).valid:
        add("postcode", "bad-postcode", "Postcode: the postcode is not recognised. Please re-enter or leave blank.")
    choice("smoking", smoking, _SMOKING, "Smoking status")
    choice("diabetes", diabetes, _DIABETES, "Diabetes status")

    if ratio is not None and (ratio < 1.0 or ratio > 11.0):
        add(
            "cholesterolHdlRatio",
            "out-of-range",
            "Cholesterol/HDL ratio: either leave blank or enter a number between 1.0 and 11.0.",
        )
    if sbp is not None and (sbp < 70 or sbp > 210):
        add("systolicBp", "out-of-range", "Systolic blood pressure: either leave blank or enter an integer between 70 and 210")
    if sbp_sd is not None and (sbp_sd < 0.0 or sbp_sd > 40.0):
        add(
            "systolicBpSd",
            "out-of-range",
            "Standard deviation of SBP: either leave blank or enter a value between 0.0 and 40.0",
        )
    pair = "You have only entered one of height and weight: please enter both or leave both blank."
    if height is None and weight is not None:
        add("heightCm", "incomplete-pair", pair)
    if height is not None and (height < 140 or height > 210):
        add("heightCm", "out-of-range", "Height: enter an integer between 140 and 210")
    if weight is None and height is not None:
        add("weightKg", "incomplete-pair", pair)
    if weight is not None and (weight < 40 or weight > 180):
        add("weightKg", "out-of-range", "Weight: enter an integer between 40 and 180")

    if inputs.existing_cvd is True:
        add(
            "existingCvd",
            "not-applicable",
            "QRISK3 is only valid for people without a diagnosis of coronary heart disease "
            "(including angina or heart attack) or stroke/transient ischaemic attack.",
        )
    if inputs.on_statins is True:
        add("onStatins", "not-applicable", "QRISK3 is only valid for people who are not on statins.")
    return QriskInputsValidation(valid=len(errors) == 0, errors=errors)

Install

fune build

With that line in your source, in a Python project (language python in fune.project), fune build resolves it and its 1 dependency, pins them in fune.lock, downloads only the Python package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:

fune add health.qrisk-inputs-validate
Download for Python health.qrisk-inputs-validate-1.0.0-python.fune · 47,633 bytes sha256 810030f0d2811c898e6c62b9b50cdd28cef58d1f7a57630c6cfc9d61fd80dfd3

The manifest, vectors and README with only the Python implementation. Install it without the registry with fune add ./health.qrisk-inputs-validate-1.0.0-python.fune, or fetch it from a terminal with fune pull health.qrisk-inputs-validate@1.0.0:python.

The whole function, every language, is one file too: health.qrisk-inputs-validate-1.0.0.fune, 61,521 bytes, sha256 02f4cd96b767c5a006fbded8d7c9fd1047eb8801fb9f7c7f37aab107d9f218c1. It installs into a project of any language.

Customise it in your app

The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.

before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.

# fune: before health.qrisk-inputs-validate

after — your function gets the result and the arguments, and returns the final result.

# fune: after health.qrisk-inputs-validate

replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.

# fune: replace validation.uk-postcode in health.qrisk-inputs-validate

step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show health.qrisk-inputs-validate --steps.

# fune: step health.qrisk-inputs-validate after <n|label>

Tests

A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.

CaseArgumentsExpected
a complete, valid input set age 64, sex male, ethnicity indian, postcode SW1A 1AA, smoking ex-smoker, diabetes type-2, family history cvd true, chronic kidney disease false, atrial fibrillation false, blood … → valid true, errors
the minimum: required fields only, every optional one null age 40, sex female, ethnicity white-or-not-stated, postcode —, smoking non-smoker, diabetes none, family history cvd false, chronic kidney disease false, atrial fibrillation false… → valid true, errors
age 25 is the youngest accepted age 25, sex female, ethnicity white-or-not-stated, postcode —, smoking non-smoker, diabetes none, family history cvd false, chronic kidney disease false, atrial fibrillation false… → valid true, errors
age 84 is the oldest accepted age 84, sex female, ethnicity white-or-not-stated, postcode —, smoking non-smoker, diabetes none, family history cvd false, chronic kidney disease false, atrial fibrillation false… → valid true, errors
age 24 is out of range age 24, sex female, ethnicity white-or-not-stated, postcode —, smoking non-smoker, diabetes none, family history cvd false, chronic kidney disease false, atrial fibrillation false… → valid false, errors ×1
age 85 is out of range age 85, sex female, ethnicity white-or-not-stated, postcode —, smoking non-smoker, diabetes none, family history cvd false, chronic kidney disease false, atrial fibrillation false… → valid false, errors ×1
missing age and sex are both required age —, sex —, ethnicity white-or-not-stated, postcode —, smoking non-smoker, diabetes none, family history cvd false, chronic kidney disease false, atrial fibrillation false, bloo… → valid false, errors ×2
an ethnicity code outside the nine is unknown age 40, sex female, ethnicity asian, postcode —, smoking non-smoker, diabetes none, family history cvd false, chronic kidney disease false, atrial fibrillation false, blood pressu… → valid false, errors ×1
a smoking description rather than its code is unknown age 40, sex female, ethnicity white-or-not-stated, postcode —, smoking light smoker (less than 10), diabetes none, family history cvd false, chronic kidney disease false, atrial f… → valid false, errors ×1
a postcode in lower case without its space is valid age 40, sex female, ethnicity white-or-not-stated, postcode sw1a1aa, smoking non-smoker, diabetes none, family history cvd false, chronic kidney disease false, atrial fibrillation… → valid true, errors
Show the other 19 tests
CaseArgumentsExpected
a blank postcode means unknown, as on the calculator age 40, sex female, ethnicity white-or-not-stated, postcode , smoking non-smoker, diabetes none, family history cvd false, chronic kidney disease false, atrial fibrillation fals… → valid true, errors
a postcode that cannot exist is reported age 40, sex female, ethnicity white-or-not-stated, postcode QQ1 1QQ, smoking non-smoker, diabetes none, family history cvd false, chronic kidney disease false, atrial fibrillation… → valid false, errors ×1
cholesterol/HDL ratio 1.0 and SD 40.0 are the inclusive limits age 40, sex female, ethnicity white-or-not-stated, postcode —, smoking non-smoker, diabetes none, family history cvd false, chronic kidney disease false, atrial fibrillation false… → valid true, errors
cholesterol/HDL ratio 11.0 and SD 0.0 are accepted age 40, sex female, ethnicity white-or-not-stated, postcode —, smoking non-smoker, diabetes none, family history cvd false, chronic kidney disease false, atrial fibrillation false… → valid true, errors
cholesterol/HDL ratio 0.9 is out of range age 40, sex female, ethnicity white-or-not-stated, postcode —, smoking non-smoker, diabetes none, family history cvd false, chronic kidney disease false, atrial fibrillation false… → valid false, errors ×1
cholesterol/HDL ratio 11.1 is out of range age 40, sex female, ethnicity white-or-not-stated, postcode —, smoking non-smoker, diabetes none, family history cvd false, chronic kidney disease false, atrial fibrillation false… → valid false, errors ×1
systolic 210 is the highest accepted age 40, sex female, ethnicity white-or-not-stated, postcode —, smoking non-smoker, diabetes none, family history cvd false, chronic kidney disease false, atrial fibrillation false… → valid true, errors
systolic 69 is out of range age 40, sex female, ethnicity white-or-not-stated, postcode —, smoking non-smoker, diabetes none, family history cvd false, chronic kidney disease false, atrial fibrillation false… → valid false, errors ×1
systolic 211 is out of range age 40, sex female, ethnicity white-or-not-stated, postcode —, smoking non-smoker, diabetes none, family history cvd false, chronic kidney disease false, atrial fibrillation false… → valid false, errors ×1
SD of systolic 40.1 is out of range age 40, sex female, ethnicity white-or-not-stated, postcode —, smoking non-smoker, diabetes none, family history cvd false, chronic kidney disease false, atrial fibrillation false… → valid false, errors ×1
height without weight is an incomplete pair age 40, sex female, ethnicity white-or-not-stated, postcode —, smoking non-smoker, diabetes none, family history cvd false, chronic kidney disease false, atrial fibrillation false… → valid false, errors ×1
weight without height is reported against height age 40, sex female, ethnicity white-or-not-stated, postcode —, smoking non-smoker, diabetes none, family history cvd false, chronic kidney disease false, atrial fibrillation false… → valid false, errors ×1
height 139 and weight 181 are both out of range age 40, sex female, ethnicity white-or-not-stated, postcode —, smoking non-smoker, diabetes none, family history cvd false, chronic kidney disease false, atrial fibrillation false… → valid false, errors ×2
height in metres is out of range, not silently converted age 40, sex female, ethnicity white-or-not-stated, postcode —, smoking non-smoker, diabetes none, family history cvd false, chronic kidney disease false, atrial fibrillation false… → valid false, errors ×1
an existing CVD diagnosis makes QRISK3 not applicable age 64, sex male, ethnicity indian, postcode SW1A 1AA, smoking ex-smoker, diabetes type-2, family history cvd true, chronic kidney disease false, atrial fibrillation false, blood … → valid false, errors ×1
taking a statin makes QRISK3 not applicable age 64, sex male, ethnicity indian, postcode SW1A 1AA, smoking ex-smoker, diabetes type-2, family history cvd true, chronic kidney disease false, atrial fibrillation false, blood … → valid false, errors ×1
several problems at once come back in field order age 90, sex male, ethnicity —, postcode SW1A 1AA, smoking ex-smoker, diabetes type 2, family history cvd true, chronic kidney disease false, atrial fibrillation false, blood press… → valid false, errors ×6
a fractional age is a type error, not a clinical one age 40.5, sex female, ethnicity white-or-not-stated, postcode —, smoking non-smoker, diabetes none, family history cvd false, chronic kidney disease false, atrial fibrillation fal… → error: age must be a whole number or null
a height with a fraction is refused: the calculator takes whole centimetres age 40, sex female, ethnicity white-or-not-stated, postcode —, smoking non-smoker, diabetes none, family history cvd false, chronic kidney disease false, atrial fibrillation false… → error: heightCm must be a whole number or null

More from the author

Every problem is reported, not just the first, in the order of the `QriskInputs` fields and then `existingCvd` and `onStatins`, each with the field name, a reason code and a message in the calculator's own wording where it has one. The result is `valid` only when there are none.

## The published input definitions

From the QRISK3 calculator form at https://qrisk.org and its client-side validation script https://qrisk.org/form.v003.js:

| Field | Required | Accepted | |---|---|---| | age | yes | whole years, 25 to 84 | | sex | yes | `female`, `male` | | ethnicity | yes | `white-or-not-stated`, `indian`, `pakistani`, `bangladeshi`, `chinese`, `other-asian`, `black-caribbean`, `black-african`, `other` | | postcode | no ("leave blank if unknown") | a valid UK postcode (checked with validation.uk-postcode) | | smoking | yes | `non-smoker`, `ex-smoker`, `light` (under 10 a day), `moderate` (10 to 19), `heavy` (20 or more) | | diabetes | yes | `none`, `type-1`, `type-2` | | cholesterolHdlRatio | no | 1.0 to 11.0 | | systolicBp | no | whole mmHg, 70 to 210 | | systolicBpSd | no | 0.0 to 40.0 (SD of at least two recent systolic readings) | | heightCm, weightKg | no, but both or neither | whole cm 140 to 210; whole kg 40 to 180 |

The eleven yes/no conditions (family history, CKD 3-5, AF, treated hypertension, migraine, rheumatoid arthritis, SLE, severe mental illness, atypical antipsychotics, regular steroid tablets, erectile dysfunction) are booleans and cannot be invalid.

The calculator states that it "is only valid if you do not already have a diagnosis of coronary heart disease (including angina or heart attack) or stroke/transient ischaemic attack, and not on statins", so `existingCvd` or `onStatins` being true is reported as `not-applicable`.

The codes for the categorical fields are this capability's own lower-case spellings of the calculator's options; the fields are plain strings, not enums, because the point is to check raw recorded values.

## Edge cases and decisions

- **Height and weight are whole numbers** in the published form ("enter an integer"). Round a recorded 172.5 cm before calling; a fractional height is refused with an error (it is a type error, thrown in every language, not a reported clinical problem), as is a fractional age or systolic pressure. A whole number sent as 170.0 is accepted. - **A lone height or weight** is reported against the missing one, with the calculator's "only entered one of height and weight" message. - **A blank postcode** (empty or spaces) is treated as unknown, as on the form. - **Units are not converted.** A height of 2 (metres) is out of range, not 200 cm. A total cholesterol typed into the ratio field cannot be told apart from a ratio if it is between 1 and 11: that is for the caller. - **Erectile dysfunction** is, as far as we know, a term of the male QRISK3 equation only (BMJ 2017; the paper's tables were not re-read for this package); the calculator's form does not reject it for women and neither does this. - The ranges are the calculator's input limits, not clinical normal ranges.

## Sources

- QRISK3 risk calculator, https://qrisk.org, and its form validation https://qrisk.org/form.v003.js (both read September 2026). - Hippisley-Cox J, Coupland C, Brindle P. Development and validation of QRISK3 risk prediction algorithms to estimate future risk of cardiovascular disease: prospective cohort study. BMJ 2017;357:j2099.

Files

PathBytes
README.md4,105
impl/python.py5,486
impl/rust.rs8,084
impl/typescript.ts5,095
vectors.json27,980