fpml 0.2.0__tar.gz → 0.3.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.3
1
+ Metadata-Version: 2.4
2
2
  Name: fpml
3
- Version: 0.2.0
3
+ Version: 0.3.1
4
4
  Summary: The FHIRPath mapping language is a data DSL designed to convert data from QuestionnaireResponse (and not only) to any FHIR Resource.
5
5
  License: MIT
6
6
  Keywords: fhir,fhirpath
@@ -21,6 +21,7 @@ Classifier: Programming Language :: Python :: 3.10
21
21
  Classifier: Programming Language :: Python :: 3.11
22
22
  Classifier: Programming Language :: Python :: 3.12
23
23
  Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Programming Language :: Python :: 3.14
24
25
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
25
26
  Requires-Dist: fhirpathpy (>=2.0.0,<3.0.0)
26
27
  Project-URL: Bug Tracker, https://github.com/beda-software/FHIRPathMappingLanguage/issues
@@ -193,6 +194,31 @@ Output:
193
194
  {'resourceType': 'Patient', 'name': [{'text': 'Name'}]}
194
195
  ```
195
196
 
197
+ ### Caching compiled expressions
198
+
199
+ Parsing FHIRPath expressions is expensive, so expressions can be compiled once and reused via
200
+ `ExpressionCache` passed through `fp_options`. The cache size is the number of compiled expressions
201
+ kept in memory, zero disables caching.
202
+
203
+ Entries are keyed by the expression only, while compilation binds the model and the user-defined
204
+ functions, so keep one long-living cache per `fp_options`. A cache is safe to share between threads.
205
+
206
+ ```python
207
+ from fhirpathpy.models import models
208
+
209
+ from fpml import ExpressionCache, resolve_template
210
+
211
+
212
+ # 1024 long expressions take up to 100mb
213
+ fp_options = {
214
+ "model": models["r4"],
215
+ "cache": ExpressionCache(max_size=1024),
216
+ }
217
+
218
+ for resource in resources:
219
+ resolve_template(resource, template, context, fp_options)
220
+ ```
221
+
196
222
  ### Handling validation errors
197
223
 
198
224
  ```python
@@ -162,6 +162,31 @@ Output:
162
162
  {'resourceType': 'Patient', 'name': [{'text': 'Name'}]}
163
163
  ```
164
164
 
165
+ ### Caching compiled expressions
166
+
167
+ Parsing FHIRPath expressions is expensive, so expressions can be compiled once and reused via
168
+ `ExpressionCache` passed through `fp_options`. The cache size is the number of compiled expressions
169
+ kept in memory, zero disables caching.
170
+
171
+ Entries are keyed by the expression only, while compilation binds the model and the user-defined
172
+ functions, so keep one long-living cache per `fp_options`. A cache is safe to share between threads.
173
+
174
+ ```python
175
+ from fhirpathpy.models import models
176
+
177
+ from fpml import ExpressionCache, resolve_template
178
+
179
+
180
+ # 1024 long expressions take up to 100mb
181
+ fp_options = {
182
+ "model": models["r4"],
183
+ "cache": ExpressionCache(max_size=1024),
184
+ }
185
+
186
+ for resource in resources:
187
+ resolve_template(resource, template, context, fp_options)
188
+ ```
189
+
165
190
  ### Handling validation errors
166
191
 
167
192
  ```python
@@ -1,5 +1,6 @@
1
1
  import importlib.metadata
2
2
 
3
+ from .core.cache import ExpressionCache
3
4
  from .core.core_exceptions import FPMLValidationError
4
5
  from .core.extract import resolve_template
5
6
 
@@ -9,4 +10,8 @@ __author__ = "beda.software"
9
10
  __license__ = "MIT"
10
11
  __copyright__ = "Copyright 2025 beda.software"
11
12
 
12
- __all__ = ["FPMLValidationError", "resolve_template"]
13
+ __all__ = [
14
+ "ExpressionCache",
15
+ "FPMLValidationError",
16
+ "resolve_template",
17
+ ]
@@ -0,0 +1,58 @@
1
+ import threading
2
+ from collections import OrderedDict
3
+ from typing import Any, Callable, Optional, cast
4
+
5
+ from fhirpathpy import compile as fhirpath_compile # type: ignore
6
+
7
+ from .core_types import FPOptions
8
+
9
+ CompiledExpression = Callable[..., list[Any]]
10
+
11
+
12
+ def compile_expression(expression: str, fp_options: Optional[FPOptions]) -> CompiledExpression:
13
+ options = cast(dict, fp_options or {}).copy()
14
+ model = options.pop("model", None)
15
+ options.pop("cache", None)
16
+
17
+ return fhirpath_compile(expression, model, options)
18
+
19
+
20
+ class ExpressionCache:
21
+ """LRU cache of compiled FHIRPath expressions.
22
+
23
+ Entries are keyed by the expression only, while compilation binds the model
24
+ and the user-defined functions, so use a separate cache per fp_options.
25
+ Zero max size disables caching. Instances are safe to share between threads.
26
+ """
27
+
28
+ def __init__(self, max_size: int) -> None:
29
+ self.max_size = max_size
30
+ self._compiled: OrderedDict[str, CompiledExpression] = OrderedDict()
31
+ self._lock = threading.Lock()
32
+
33
+ def compile(self, expression: str, fp_options: Optional[FPOptions]) -> CompiledExpression:
34
+ with self._lock:
35
+ cached = self._compiled.get(expression)
36
+ if cached is not None:
37
+ self._compiled.move_to_end(expression)
38
+
39
+ return cached
40
+
41
+ # Compiling outside the lock, so that it does not hold up the other threads
42
+ compiled = compile_expression(expression, fp_options)
43
+
44
+ if self.max_size > 0:
45
+ with self._lock:
46
+ self._compiled[expression] = compiled
47
+ if len(self._compiled) > self.max_size:
48
+ self._compiled.popitem(last=False)
49
+
50
+ return compiled
51
+
52
+ def clear(self) -> None:
53
+ with self._lock:
54
+ self._compiled.clear()
55
+
56
+ @property
57
+ def size(self) -> int:
58
+ return len(self._compiled)
@@ -1,7 +1,10 @@
1
- from typing import Any, Callable, Optional, TypedDict, Union
1
+ from typing import TYPE_CHECKING, Any, Callable, Optional, TypedDict, Union
2
2
 
3
3
  from typing_extensions import NotRequired
4
4
 
5
+ if TYPE_CHECKING:
6
+ from .cache import ExpressionCache
7
+
5
8
  Resource = dict[str, Any]
6
9
  Node = Any
7
10
  DictNode = dict[str, Any]
@@ -39,6 +42,9 @@ class FPOptions(TypedDict):
39
42
  A table of user-defined functions that
40
43
  can be used in FHIRPath expressions during template processing.
41
44
  See https://github.com/beda-software/fhirpath-py?tab=readme-ov-file#user-defined-functions
45
+ cache (Optional[ExpressionCache]):
46
+ A cache of compiled expressions, e.g. ExpressionCache(max_size=1024).
47
+ Expressions are compiled on every evaluation when it's not passed.
42
48
 
43
49
  See Also:
44
50
  FHIRPath py Documentation:
@@ -47,6 +53,7 @@ class FPOptions(TypedDict):
47
53
 
48
54
  model: NotRequired[Model]
49
55
  userInvocationTable: NotRequired[UserInvocationTable]
56
+ cache: NotRequired["ExpressionCache"]
50
57
 
51
58
 
52
59
  class MatcherResult(TypedDict):
@@ -1,10 +1,9 @@
1
1
  import re
2
2
  from typing import Any, Optional, cast
3
3
 
4
- from fhirpathpy import evaluate # type: ignore
5
-
6
4
  from fpml.core.guarded_resource import guarded_resource
7
5
 
6
+ from .cache import compile_expression
8
7
  from .constants import root_node_key, undefined
9
8
  from .core_exceptions import FPMLValidationError
10
9
  from .core_types import (
@@ -395,10 +394,15 @@ def evaluate_expression(
395
394
  context: Context,
396
395
  fp_options: Optional[FPOptions] = None,
397
396
  ) -> list[Any]:
398
- fp_options_copy = cast(dict, fp_options or {}).copy()
399
- model = fp_options_copy.pop("model", None)
397
+ cache = (fp_options or {}).get("cache")
400
398
 
401
399
  try:
402
- return evaluate(resource, expression, context, model, options=fp_options_copy)
400
+ compiled = (
401
+ cache.compile(expression, fp_options)
402
+ if cache
403
+ else compile_expression(expression, fp_options)
404
+ )
405
+
406
+ return compiled(resource, context)
403
407
  except Exception as exc:
404
408
  raise FPMLValidationError(f"Cannot evaluate '{expression}': {exc}", path) from exc
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "fpml"
3
- version = "0.2.0"
3
+ version = "0.3.1"
4
4
  description = "The FHIRPath mapping language is a data DSL designed to convert data from QuestionnaireResponse (and not only) to any FHIR Resource."
5
5
  authors = [{ name = "Beda Software", email = "ilya@beda.software" }]
6
6
  maintainers = [
File without changes
File without changes
File without changes
File without changes
File without changes