pydantic-fhirpath
Native FHIRPath queries for fhir.resources 8.3, Pydantic v2, and Python 3.14.
Derived from fhirpathpy 2.2.4, retaining
its MIT-licensed ANTLR grammar and adding a fully typed native runtime.
Install with Python 3.14:
uv add pydantic-fhirpath
from fhir.resources.patient import Patient
from pydantic_fhirpath import compile, path, var
patient = Patient.model_validate({
"name": [{"use": "official", "given": ["example"]}],
})
query = compile(
"Patient.name.where(use = %use).given.first()",
output_type=str,
)
assert query(patient, {"use": "official"}) == ["example"]
# Same operation without creating, escaping, or parsing a query string:
expression = (
path("Patient", "name")
.where(path("use").eq(var("use")))
.field("given")
.first()
)
assert compile(expression, output_type=str)(patient, {"use": "official"}) == ["example"]
evaluate(resource, expression, context=None) returns a collection. Public inputs
use the covariant InputValue contract: concrete lists such as list[Patient],
readonly sequences and mappings, and native models work without casts. Pydantic
normalizes container shapes at the boundary while preserving resource identity
and avoiding repeated resource validators. Context bindings and literal() use
the same contract. compile
creates a reusable query with .first() and cardinality-checking .one() helpers.
compile_as_array and compile_as_first additionally check the input model class.
literal(value) embeds a native constant in a fluent expression; var(name) binds
runtime data. Neither constructs or interpolates FHIRPath text.
expression.binary(operator, other) supports arithmetic, ordering, membership,
set and Boolean operators. Its BinaryOperator argument is statically typed and
validated with Pydantic; both operands remain native syntax nodes.
is_type(), as_type() and of_type() accept an actual Pydantic class or a
FHIR/System type name. For example, path("gender").is_type("FHIR.string") uses
the declared primitive hierarchy, while path().as_type(Patient) checks the real
model class and preserves the instance. Type names are syntax data and never
interpolated into a query string.
Evaluation reads Pydantic fields directly. FHIR aliases (Encounter.class), choice
groups (Observation.value), and primitive extensions come from model metadata.
Selected models retain identity; dates, times, Decimals and bytes retain their
Python types. No model_dump(), JSON round trip, input mutation, or external FHIR
model table is used. R5 and R4B share the same reader. Cached plans contain syntax,
field metadata and validators; per-call variables stay out of caches.
Pydantic invariants
from typing import Annotated
from pydantic import BaseModel
from pydantic_fhirpath import FHIRPathConstraint
active = FHIRPathConstraint(
expression="active = true",
message="Resource must be active",
)
class Envelope(BaseModel):
resource: Annotated[Patient, active.after_validator()]
Constraints require exactly [True]. Result adapters use strict Pydantic validation,
so a query declared as str cannot silently convert a Boolean or number. For
custom result schemas, CompiledQuery(node=..., adapter=TypeAdapter[...](...))
accepts an already-built adapter, including an Annotated type with validators.
See COMPATIBILITY.md for measured feature coverage, audit counts and remaining gaps.
Supported scope
Version 0.1 implements native navigation, aliases, choices, primitive extensions,
variables, indexing, filtering, projection, repetition, aggregation, collection
operators, three-valued Boolean operators, numeric and string functions, native
scalar conversions, typed quantity literals/conversion/arithmetic, and
precision-aware temporal literals and comparisons. Unsupported functions raise UnsupportedFeatureError; there is no serialization fallback.
This is not a drop-in implementation of every fhirpathpy feature.
type() returns a typed TypeInfo model. Declared FHIR primitive subtypes are
retained separately from their Python representations: type() retains concrete primitive identity, while is(), as() and ofType()
recognize FHIR primitive specializations (for example, code specializes string
and uuid specializes uri). is() still distinguishes FHIR primitives from System
types; ofType() also supports implicit System conversion. getValue() returns the underlying System value. Raw dictionaries support ordinary fields; native choice
resolution requires FHIR models. Use R4B or R5 models for clinical resources.
Partial temporal results use the frozen TemporalValue Pydantic model; complete
values retain Python temporal types. Missing precision produces an indeterminate
comparison where required. Calendar arithmetic clamps month-end dates, retains
partial precision, and preserves fractional seconds. Fixed UCUM durations
(wk, d, h, min, s, ms) work as their corresponding calendar components.
Mean UCUM years/months (a, mo) require explicit conversion to calendar units. literal(TemporalValue(kind="DateTime", year=2018))
works without query text. Text literals also support partial DateTimes such as
@2018T, @2018-02T, and @2018-02-02T.
Quantity results use the frozen QuantityValue Pydantic model. Known conversions
cover mass, length, volume, time and their products/quotients. Other UCUM codes
remain opaque and exact-match only; this is not a complete UCUM catalogue. Native
FHIR quantities require a UCUM system and code for implicit conversion, and a
comparator cannot silently become an exact value. Calendar years/months remain
indeterminate against their mean UCUM counterparts, while fixed durations from
weeks through milliseconds are interchangeable; conversion uses Decimal without integer rounding. Quantity equivalence carries
input precision through unit conversion; exact equality and converted values
remain exact.
EvaluationOptions registers eager CustomFunction and deferred CustomMacro
definitions, a trace sink, and a native reference resolver. Handlers receive FunctionCall and return native
collections; trace sinks receive TraceEvent. Pass options= to compile,
evaluate, or the typed compile helpers. Registration, argument counts and return
boundaries are validated with Pydantic. Builtin overrides are supported.
resolve() indexes native Bundle entries and contained-resource scopes within one
evaluation, then consults the optional caller resolver. It preserves resource
identity and performs no implicit network access. An unconfigured trace() keeps
its input and produces no console output. FHIR model subclasses with their own
Pydantic validators retain their logical resource type.
The original fhirpathpy/ source remains as the comparison baseline and is not
shipped in the new wheel or checked as handwritten native code. The retained
Python regression tests have typed signatures, run with mise run test:baseline,
and are checked alongside every test by hk. The native fixture runner owns YAML
conformance coverage; the former root-level YAML collector is removed.
mise run sync installs locked dependencies and repository-scoped hk hooks.
Git hooks and CI share mise run check, which runs the complete pre-push gate:
both test suites plus the same linters used by pre-commit. Executable tasks live
in mise-tasks/ and use Bash, the existing CI shell. Mise pins Python, uv and hk
for local and CI execution.
CI runs Ruff (including all annotation rules), ty (all = "error") and Pyright
(typeCheckingMode = "strict") through hk. All handwritten source, tests, tools
and dependency stubs are in scope. Only generated ANTLR implementation files are
excluded from native source checking; their adjacent interfaces are checked.
typings/ supplies narrow interfaces for the untyped ANTLR runtime and legacy
comparison APIs. It supplies no Python-version compatibility shims or native
package annotations; the native package carries its own annotations and
py.typed.
Development
mise run sync
mise run check
mise run benchmark
mise run profile
mise run build
mise run smoke
hk check --all enforces Ruff, formatting, strict Pyright, ty with every rule set
to error, and lock freshness. Handwritten runtime and native tests contain no Any,
casts, or type suppression comments. The benchmark compares compiled native queries
against compiled fhirpathpy plus model_dump(by_alias=True, exclude_none=True);
it reports timings without making hardware-dependent pass/fail claims.
mise run parity executes every original YAML scenario against native validated
resources and writes dist/parity-report.json. It exits nonzero while any enabled
case fails, uses an unsupported feature, lacks an expectation, or has an input
rejected by FHIR validation. Upstream-disabled cases remain visible. Error cases
are actually evaluated; an unsupported feature never satisfies an expected error.
The audit compares native models, quantities and temporal values with their
analogous expected values rather than requiring JSON-shaped results.
The source grammar is grammar/FHIRPath.g4. mise run grammar regenerates the
Python lexer and parser using the official ANTLR 4.13.2 JAR, verified by SHA-256.
Regeneration requires Java on the mise environment PATH.
mise run parity:hl7 audits the complete pinned official R4/R4B/R5 XML corpora
using native FHIR model parsing. It records every assertion, including unsupported
configurations and rejected inputs, in dist/hl7-report.json.
mise run smoke builds the wheel, checks its typed package and grammar files,
and runs native queries and Pydantic constraints in a subprocess outside the
checkout. The probe requires its imports to come from the wheel archive, preserves
model identity and validator counts, and checks that the legacy engine is not
loaded. CI runs this check after the full native test and typing gate.
Deferred and variadic callbacks
Use CustomMacro when the callback must choose which expressions evaluate.
An argument's evaluate() uses its bound FHIR focus and retains primitive
metadata, extensions, resource ownership, $index and $total. Supply
evaluate(new_focus, index=...) to evaluate per element; the original index
resolves duplicate scalar provenance. Explicit None means an empty focus.
from pydantic import BaseModel, Field
from pydantic_fhirpath import CustomMacro, EvaluationOptions, FunctionArity, MacroCall
from pydantic_fhirpath.types import Collection
class ChoicePolicy(BaseModel):
minimum_results: int = Field(default=1, ge=1, strict=True)
def first_present(self, call: MacroCall) -> Collection:
for argument in call.arguments:
if len(result := argument.evaluate()) >= self.minimum_results:
return result
return []
policy = ChoicePolicy()
options = EvaluationOptions(functions=(
CustomMacro(
name="firstPresent",
handler=policy.first_present,
arity=FunctionArity(minimum=1),
),
))
A tuple such as arity=(0, 2) remains a closed set. FunctionArity(minimum=1, maximum=3) accepts an inclusive range; omitting maximum permits unbounded
arguments. These forms work for eager functions and macros, and arity errors
occur before any argument evaluates. Pydantic registration dictionaries select
a macro with kind="macro"; the eager default is kind="function". Unknown
registration/options fields are rejected rather than silently ignored.
Use a Pydantic schema or TypeAdapter inside the handler for scalar argument
constraints. Deferred arguments also expose name for identifier/type arguments
without evaluating a path. Callback results are native values: model identity is
preserved, and returned scalars have System types rather than inferred field
provenance. Generic callback state belongs to the caller; compiled plans never
cache a call's bound arguments or focus.
Numeric and temporal precision
precision() reports Decimal fractional places and temporal component digits.
Trailing zeros and partial date/time precision survive conversions and arithmetic
within a query. Native datetime/time inputs expose six microsecond places;
TemporalValue preserves explicitly declared precision. Complete results remain
native Python values, so a subsequent query sees their native representation.
Typed model outputs preserve existing instances and do not re-run their validators. Other outputs use strict Pydantic validation. Typed plans share their result adapters; explicit query options and evaluation state stay outside the plan cache. Numeric operations use an isolated Decimal context with a 28-digit minimum and additional precision for exact arithmetic, unit scaling and integer powers. Power expansions exceeding 10,000 estimated coefficient digits use the standard precision policy to bound their working memory.
Publishing
Tag a verified commit with the matching project version, such as pydantic-fhirpath-v0.1.0.
The publish-pypi.yaml workflow checks both suites, builds and validates the archives,
and publishes those exact files with PyPI Trusted Publishing. A manual workflow
run verifies the release without uploading it. PyPI registration uses owner
NorthIsUp, repository pydantic-fhirpath, workflow publish-pypi.yaml, environment
pypi, and project pydantic-fhirpath.
Metadata
Release files for pydantic-fhirpath 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| pydantic_fhirpath-0.1.0.tar.gz | 362.6 kB | Without provenance | Details for pydantic_fhirpath-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pydantic_fhirpath-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for pydantic_fhirpath-0.1.0-py3-none-any.whl |
Total release size: 426.6 kB
Release files / pydantic_fhirpath-0.1.0.tar.gz
| Download URL | pydantic_fhirpath-0.1.0.tar.gz |
|---|---|
| Size | 362.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
1be8e48d3e8f20afcc7a8bae72f89c33b732d308c2796402df19a70779b00f65
|
|
BLAKE2b-256 checksum How to use checksums |
75ba1a949870ccb96e818bc2a9de51b5df90d6de191164e0705a3e3b204d322f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / pydantic_fhirpath-0.1.0-py3-none-any.whl
| Download URL | pydantic_fhirpath-0.1.0-py3-none-any.whl |
|---|---|
| Size | 64.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
7ecc95c26fec7868bd3624b4e41aa9ee00eca29c7859f458b4f86cb41b257f7e
|
|
BLAKE2b-256 checksum How to use checksums |
9762f72acc91c0fbc65194ed1d24543a6593ee0c15302b18c5286244352f8748
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for pydantic-fhirpath 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.