fpml 0.3.1__tar.gz → 2.0.0__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
1
  Metadata-Version: 2.4
2
2
  Name: fpml
3
- Version: 0.3.1
3
+ Version: 2.0.0
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
@@ -8,7 +8,7 @@ Author: Beda Software
8
8
  Author-email: ilya@beda.software
9
9
  Maintainer: Vadim Laletin
10
10
  Maintainer-email: vadim@beda.software
11
- Requires-Python: >=3.9
11
+ Requires-Python: >=3.10
12
12
  Classifier: Development Status :: 5 - Production/Stable
13
13
  Classifier: Environment :: Web Environment
14
14
  Classifier: Intended Audience :: Developers
@@ -16,14 +16,15 @@ Classifier: License :: OSI Approved :: MIT License
16
16
  Classifier: Operating System :: OS Independent
17
17
  Classifier: Programming Language :: Python
18
18
  Classifier: Programming Language :: Python :: 3
19
- Classifier: Programming Language :: Python :: 3.9
20
19
  Classifier: Programming Language :: Python :: 3.10
21
20
  Classifier: Programming Language :: Python :: 3.11
22
21
  Classifier: Programming Language :: Python :: 3.12
23
22
  Classifier: Programming Language :: Python :: 3.13
24
23
  Classifier: Programming Language :: Python :: 3.14
24
+ Classifier: Programming Language :: Python :: 3.15
25
25
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
26
- Requires-Dist: fhirpathpy (>=2.0.0,<3.0.0)
26
+ Requires-Dist: fhirpathpy (>=3.0.1,<4.0.0)
27
+ Requires-Dist: typing-extensions (>=4.0.0)
27
28
  Project-URL: Bug Tracker, https://github.com/beda-software/FHIRPathMappingLanguage/issues
28
29
  Project-URL: Documentation, https://github.com/beda-software/FHIRPathMappingLanguage/tree/main/python/README.md
29
30
  Project-URL: Homepage, https://github.com/beda-software/FHIRPathMappingLanguage/tree/main/python
@@ -57,8 +58,8 @@ result = resolve_template(
57
58
  resource,
58
59
  template,
59
60
  context=None,
60
- fp_options=None,
61
- strict=False
61
+ strict=False,
62
+ evaluate=None
62
63
  )
63
64
  ```
64
65
 
@@ -67,8 +68,8 @@ result = resolve_template(
67
68
  - resource (Resource): The input FHIR resource to process.
68
69
  - template (Any): The template describing the transformation.
69
70
  - context (Optional[Context], optional): Additional context data. Defaults to None.
70
- - fp_options (Optional[FPOptions], optional): Options for controlling FHIRPath evaluation. Defaults to None.
71
71
  - strict (bool, optional): Whether to enforce strict mode. Defaults to False. See more details on [strict mode](https://github.com/beda-software/FHIRPathMappingLanguage/tree/main?tab=readme-ov-file#strict-mode).
72
+ - evaluate (Optional[Evaluate], optional): Evaluates one FHIRPath expression against a resource and a context. Defaults to `make_evaluator()`, which compiles every expression on every evaluation.
72
73
 
73
74
  ### Returns:
74
75
 
@@ -129,9 +130,10 @@ Output:
129
130
  ### Using FHIR data-model
130
131
 
131
132
  ```python
132
- from fpml import resolve_template
133
133
  from fhirpathpy.models import models
134
134
 
135
+ from fpml import make_evaluator, resolve_template
136
+
135
137
 
136
138
  template = {
137
139
  "resourceType": "Patient",
@@ -144,11 +146,9 @@ template = {
144
146
 
145
147
  context = {}
146
148
 
147
- fp_options = {
148
- "model": models["r4"]
149
- }
149
+ evaluate = make_evaluator(models["r4"])
150
150
 
151
- result = resolve_template(resource, template, context, fp_options)
151
+ result = resolve_template(resource, template, context, evaluate=evaluate)
152
152
  print(result)
153
153
  ```
154
154
 
@@ -160,7 +160,7 @@ Output:
160
160
  ### Using user-defined functions
161
161
 
162
162
  ```python
163
- from fpml import resolve_template
163
+ from fpml import make_evaluator, resolve_template
164
164
 
165
165
 
166
166
  template = {
@@ -181,11 +181,9 @@ user_invocation_table = {
181
181
  }
182
182
  }
183
183
 
184
- fp_options = {
185
- "userInvocationTable": user_invocation_table
186
- }
184
+ evaluate = make_evaluator(options={"userInvocationTable": user_invocation_table})
187
185
 
188
- result = resolve_template(resource, template, context, fp_options)
186
+ result = resolve_template(resource, template, context, evaluate=evaluate)
189
187
  print(result)
190
188
  ```
191
189
 
@@ -194,31 +192,45 @@ Output:
194
192
  {'resourceType': 'Patient', 'name': [{'text': 'Name'}]}
195
193
  ```
196
194
 
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.
195
+ ### Using a custom evaluator
202
196
 
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.
197
+ By default every expression is compiled on every evaluation, which is expensive. Pass an `evaluate`
198
+ function to reuse compiled expressions, cached the way your application needs. It takes a resource,
199
+ an expression and a context, and returns the list of results.
205
200
 
206
201
  ```python
202
+ from functools import lru_cache
203
+
204
+ from fhirpathpy import compile
207
205
  from fhirpathpy.models import models
208
206
 
209
- from fpml import ExpressionCache, resolve_template
207
+ from fpml import resolve_template
210
208
 
211
209
 
212
- # 1024 long expressions take up to 100mb
213
- fp_options = {
214
- "model": models["r4"],
215
- "cache": ExpressionCache(max_size=1024),
216
- }
210
+ @lru_cache(maxsize=1024)
211
+ def cached_compile(expression, model_name):
212
+ return compile(expression, models.get(model_name))
213
+
214
+
215
+ def evaluate(resource, expression, context):
216
+ return cached_compile(expression, "r4")(resource, context)
217
+
217
218
 
218
219
  for resource in resources:
219
- resolve_template(resource, template, context, fp_options)
220
+ resolve_template(resource, template, context, evaluate=evaluate)
220
221
  ```
221
222
 
223
+ Compilation binds the model and the user-defined functions, so cache entries are only reusable for
224
+ the same pair. Keep them in the key, like `model_name` above, when the application evaluates against
225
+ more than one model, otherwise expressions compiled for one silently resolve against the other.
226
+
227
+ A compiled expression retains its parsed AST, so the memory cost grows with the expression length:
228
+ `1024` of them take about 11mb for short expressions and up to 290mb for 1kb ones. Size the cache for
229
+ the number of distinct expressions your templates and questionnaires actually contain.
230
+
231
+ `make_evaluator` builds the default evaluator from a model and a user-defined function table, as the
232
+ examples above do. A custom evaluator applies both itself.
233
+
222
234
  ### Handling validation errors
223
235
 
224
236
  ```python
@@ -25,8 +25,8 @@ result = resolve_template(
25
25
  resource,
26
26
  template,
27
27
  context=None,
28
- fp_options=None,
29
- strict=False
28
+ strict=False,
29
+ evaluate=None
30
30
  )
31
31
  ```
32
32
 
@@ -35,8 +35,8 @@ result = resolve_template(
35
35
  - resource (Resource): The input FHIR resource to process.
36
36
  - template (Any): The template describing the transformation.
37
37
  - context (Optional[Context], optional): Additional context data. Defaults to None.
38
- - fp_options (Optional[FPOptions], optional): Options for controlling FHIRPath evaluation. Defaults to None.
39
38
  - strict (bool, optional): Whether to enforce strict mode. Defaults to False. See more details on [strict mode](https://github.com/beda-software/FHIRPathMappingLanguage/tree/main?tab=readme-ov-file#strict-mode).
39
+ - evaluate (Optional[Evaluate], optional): Evaluates one FHIRPath expression against a resource and a context. Defaults to `make_evaluator()`, which compiles every expression on every evaluation.
40
40
 
41
41
  ### Returns:
42
42
 
@@ -97,9 +97,10 @@ Output:
97
97
  ### Using FHIR data-model
98
98
 
99
99
  ```python
100
- from fpml import resolve_template
101
100
  from fhirpathpy.models import models
102
101
 
102
+ from fpml import make_evaluator, resolve_template
103
+
103
104
 
104
105
  template = {
105
106
  "resourceType": "Patient",
@@ -112,11 +113,9 @@ template = {
112
113
 
113
114
  context = {}
114
115
 
115
- fp_options = {
116
- "model": models["r4"]
117
- }
116
+ evaluate = make_evaluator(models["r4"])
118
117
 
119
- result = resolve_template(resource, template, context, fp_options)
118
+ result = resolve_template(resource, template, context, evaluate=evaluate)
120
119
  print(result)
121
120
  ```
122
121
 
@@ -128,7 +127,7 @@ Output:
128
127
  ### Using user-defined functions
129
128
 
130
129
  ```python
131
- from fpml import resolve_template
130
+ from fpml import make_evaluator, resolve_template
132
131
 
133
132
 
134
133
  template = {
@@ -149,11 +148,9 @@ user_invocation_table = {
149
148
  }
150
149
  }
151
150
 
152
- fp_options = {
153
- "userInvocationTable": user_invocation_table
154
- }
151
+ evaluate = make_evaluator(options={"userInvocationTable": user_invocation_table})
155
152
 
156
- result = resolve_template(resource, template, context, fp_options)
153
+ result = resolve_template(resource, template, context, evaluate=evaluate)
157
154
  print(result)
158
155
  ```
159
156
 
@@ -162,31 +159,45 @@ Output:
162
159
  {'resourceType': 'Patient', 'name': [{'text': 'Name'}]}
163
160
  ```
164
161
 
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.
162
+ ### Using a custom evaluator
170
163
 
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.
164
+ By default every expression is compiled on every evaluation, which is expensive. Pass an `evaluate`
165
+ function to reuse compiled expressions, cached the way your application needs. It takes a resource,
166
+ an expression and a context, and returns the list of results.
173
167
 
174
168
  ```python
169
+ from functools import lru_cache
170
+
171
+ from fhirpathpy import compile
175
172
  from fhirpathpy.models import models
176
173
 
177
- from fpml import ExpressionCache, resolve_template
174
+ from fpml import resolve_template
178
175
 
179
176
 
180
- # 1024 long expressions take up to 100mb
181
- fp_options = {
182
- "model": models["r4"],
183
- "cache": ExpressionCache(max_size=1024),
184
- }
177
+ @lru_cache(maxsize=1024)
178
+ def cached_compile(expression, model_name):
179
+ return compile(expression, models.get(model_name))
180
+
181
+
182
+ def evaluate(resource, expression, context):
183
+ return cached_compile(expression, "r4")(resource, context)
184
+
185
185
 
186
186
  for resource in resources:
187
- resolve_template(resource, template, context, fp_options)
187
+ resolve_template(resource, template, context, evaluate=evaluate)
188
188
  ```
189
189
 
190
+ Compilation binds the model and the user-defined functions, so cache entries are only reusable for
191
+ the same pair. Keep them in the key, like `model_name` above, when the application evaluates against
192
+ more than one model, otherwise expressions compiled for one silently resolve against the other.
193
+
194
+ A compiled expression retains its parsed AST, so the memory cost grows with the expression length:
195
+ `1024` of them take about 11mb for short expressions and up to 290mb for 1kb ones. Size the cache for
196
+ the number of distinct expressions your templates and questionnaires actually contain.
197
+
198
+ `make_evaluator` builds the default evaluator from a model and a user-defined function table, as the
199
+ examples above do. A custom evaluator applies both itself.
200
+
190
201
  ### Handling validation errors
191
202
 
192
203
  ```python
@@ -1,7 +1,8 @@
1
1
  import importlib.metadata
2
2
 
3
- from .core.cache import ExpressionCache
4
3
  from .core.core_exceptions import FPMLValidationError
4
+ from .core.core_types import Evaluate
5
+ from .core.evaluator import FPOptions, make_evaluator
5
6
  from .core.extract import resolve_template
6
7
 
7
8
  __title__ = "fpml"
@@ -11,7 +12,9 @@ __license__ = "MIT"
11
12
  __copyright__ = "Copyright 2025 beda.software"
12
13
 
13
14
  __all__ = [
14
- "ExpressionCache",
15
+ "Evaluate",
15
16
  "FPMLValidationError",
17
+ "FPOptions",
18
+ "make_evaluator",
16
19
  "resolve_template",
17
20
  ]
@@ -0,0 +1,41 @@
1
+ from typing import Any, Callable, Optional, TypedDict, Union
2
+
3
+ from typing_extensions import NotRequired
4
+
5
+ Resource = dict[str, Any]
6
+ Node = Any
7
+ DictNode = dict[str, Any]
8
+ StrNode = str
9
+ Context = dict[str, Any]
10
+
11
+ Path = list[Union[str, int]]
12
+
13
+
14
+ class UserFnDefinition(TypedDict):
15
+ fn: Callable
16
+ arity: dict[int, list[str]]
17
+ nullable: NotRequired[bool]
18
+
19
+
20
+ UserInvocationTable = dict[str, UserFnDefinition]
21
+
22
+
23
+ Evaluate = Callable[[Resource, str, Context], list[Any]]
24
+
25
+
26
+ class MatcherResult(TypedDict):
27
+ node: Optional[Node]
28
+
29
+
30
+ Matcher = Callable[
31
+ [
32
+ Path,
33
+ Resource,
34
+ DictNode,
35
+ Context,
36
+ Evaluate,
37
+ ],
38
+ Optional[MatcherResult],
39
+ ]
40
+
41
+ Transformer = Callable[[Path, Node, Context], tuple[Node, Context]]
@@ -0,0 +1,16 @@
1
+ from typing import Any, Optional
2
+
3
+ from fhirpathpy import Model
4
+ from fhirpathpy import Options as FPOptions
5
+ from fhirpathpy import evaluate as fhirpath_evaluate
6
+
7
+ from .core_types import Context, Evaluate, Resource
8
+
9
+
10
+ def make_evaluator(model: Optional[Model] = None, options: Optional[FPOptions] = None) -> Evaluate:
11
+ """Builds the default evaluator, which compiles every expression on every evaluation."""
12
+
13
+ def evaluate(resource: Resource, expression: str, context: Context) -> list[Any]:
14
+ return fhirpath_evaluate(resource, expression, context, model, options)
15
+
16
+ return evaluate
@@ -3,13 +3,12 @@ from typing import Any, Optional, cast
3
3
 
4
4
  from fpml.core.guarded_resource import guarded_resource
5
5
 
6
- from .cache import compile_expression
7
6
  from .constants import root_node_key, undefined
8
7
  from .core_exceptions import FPMLValidationError
9
8
  from .core_types import (
10
9
  Context,
11
10
  DictNode,
12
- FPOptions,
11
+ Evaluate,
13
12
  Matcher,
14
13
  MatcherResult,
15
14
  Node,
@@ -18,6 +17,7 @@ from .core_types import (
18
17
  StrNode,
19
18
  Transformer,
20
19
  )
20
+ from .evaluator import make_evaluator
21
21
  from .utils import flatten, omit_key
22
22
 
23
23
 
@@ -25,8 +25,9 @@ def resolve_template(
25
25
  resource: Resource,
26
26
  template: Any,
27
27
  context: Optional[Context] = None,
28
- fp_options: Optional[FPOptions] = None,
28
+ *,
29
29
  strict: bool = False,
30
+ evaluate: Optional[Evaluate] = None,
30
31
  ) -> Any:
31
32
  """
32
33
  Processes a given template with the specified resource and optional context.
@@ -39,10 +40,12 @@ def resolve_template(
39
40
  resource (Resource): The input FHIR resource to process.
40
41
  template (Any): The template describing the transformation.
41
42
  context (Optional[Context], optional): Additional context data. Defaults to None.
42
- fp_options (Optional[FPOptions], optional): Options for controlling FHIRPath evaluation. Defaults to None.
43
43
  strict (bool, optional): Whether to enforce strict mode. Defaults to False.
44
44
  See more details on
45
45
  [strict mode](https://github.com/beda-software/FHIRPathMappingLanguage/tree/main?tab=readme-ov-file#strict-mode).
46
+ evaluate (Optional[Evaluate], optional): Evaluates one FHIRPath expression against a
47
+ resource and a context. Defaults to make_evaluator(), which compiles every
48
+ expression on every evaluation.
46
49
 
47
50
  Returns:
48
51
  Any: The processed output based on the template.
@@ -53,14 +56,14 @@ def resolve_template(
53
56
  See Also:
54
57
  FHIRPathMappingLanguage Specification:
55
58
  https://github.com/beda-software/FHIRPathMappingLanguage/tree/main?tab=readme-ov-file#specification
56
- """ # noqa: E501
59
+ """
57
60
  result = resolve_template_recur(
58
61
  [],
59
62
  guarded_resource if strict else resource,
60
63
  template,
61
64
  # Pass resource as context because original is overriden by strict mode
62
65
  {"context": resource, **(context or {})},
63
- fp_options=fp_options,
66
+ evaluate or make_evaluator(),
64
67
  )
65
68
 
66
69
  return None if result == undefined else result
@@ -71,13 +74,13 @@ def resolve_template_recur(
71
74
  resource: Resource,
72
75
  template: Any,
73
76
  context: Context,
74
- fp_options: Optional[FPOptions] = None,
77
+ evaluate: Evaluate,
75
78
  ) -> Any:
76
79
  result = iterate_node(
77
80
  start_path,
78
81
  {root_node_key: template},
79
82
  context or {},
80
- lambda path, node, context: process_node(path, resource, node, context, fp_options),
83
+ lambda path, node, context: process_node(path, resource, node, context, evaluate),
81
84
  )
82
85
  if isinstance(result, dict):
83
86
  return result.get(root_node_key, undefined)
@@ -90,10 +93,10 @@ def process_node(
90
93
  resource: Resource,
91
94
  node: Node,
92
95
  context: Context,
93
- fp_options: Optional[FPOptions],
96
+ evaluate: Evaluate,
94
97
  ) -> tuple[Node, Context]:
95
98
  if isinstance(node, dict):
96
- new_node, new_context = process_assign_block(path, resource, node, context, fp_options)
99
+ new_node, new_context = process_assign_block(path, resource, node, context, evaluate)
97
100
 
98
101
  matchers: list[Matcher] = [
99
102
  process_context_block,
@@ -103,14 +106,14 @@ def process_node(
103
106
  ]
104
107
 
105
108
  for matcher in matchers:
106
- result = matcher(path, resource, new_node, new_context, fp_options)
109
+ result = matcher(path, resource, new_node, new_context, evaluate)
107
110
  if result:
108
111
  return result["node"], new_context
109
112
 
110
113
  return new_node, new_context
111
114
 
112
115
  if isinstance(node, str):
113
- return process_template_string(path, resource, node, context, fp_options), context
116
+ return process_template_string(path, resource, node, context, evaluate), context
114
117
 
115
118
  return node, context
116
119
 
@@ -159,14 +162,14 @@ def process_template_string(
159
162
  resource: Resource,
160
163
  node: StrNode,
161
164
  context: Context,
162
- fp_options: Optional[FPOptions],
165
+ evaluate: Evaluate,
163
166
  ) -> Any:
164
167
  array_template_regexp = re.compile(r"{\[\s*([\s\S]+?)\s*\]}")
165
168
 
166
169
  match = array_template_regexp.match(node)
167
170
  if match:
168
171
  expr = match.group(1)
169
- return evaluate_expression(path, resource, expr, context, fp_options)
172
+ return evaluate_expression(path, resource, expr, context, evaluate)
170
173
 
171
174
  single_template_regexp = re.compile(r"{{\+?\s*([\s\S]+?)\s*\+?}}")
172
175
  result = node
@@ -174,7 +177,7 @@ def process_template_string(
174
177
  for match in single_template_regexp.finditer(node):
175
178
  expr = match.group(1)
176
179
  try:
177
- replacement = evaluate_expression(path, resource, expr, context, fp_options)[0]
180
+ replacement = evaluate_expression(path, resource, expr, context, evaluate)[0]
178
181
  except IndexError:
179
182
  return None if match.group(0).startswith("{{+") else undefined
180
183
  if match.group(0) == node:
@@ -189,7 +192,7 @@ def process_context_block(
189
192
  resource: Resource,
190
193
  node: DictNode,
191
194
  context: Context,
192
- fp_options: Optional[FPOptions],
195
+ evaluate: Evaluate,
193
196
  ) -> Optional[MatcherResult]:
194
197
  keys = list(node.keys())
195
198
  context_regexp = re.compile(r"{{\s*(.+?)\s*}}")
@@ -202,10 +205,10 @@ def process_context_block(
202
205
  if len(keys) > 1:
203
206
  raise FPMLValidationError("Context block must be presented as single key", path)
204
207
 
205
- answers = evaluate_expression(path, resource, expr, context, fp_options)
208
+ answers = evaluate_expression(path, resource, expr, context, evaluate)
206
209
  return {
207
210
  "node": [
208
- resolve_template_recur(path, answer, node[context_key], context, fp_options)
211
+ resolve_template_recur(path, answer, node[context_key], context, evaluate)
209
212
  for answer in answers
210
213
  ]
211
214
  }
@@ -218,7 +221,7 @@ def process_for_block(
218
221
  resource: Resource,
219
222
  node: DictNode,
220
223
  context: Context,
221
- fp_options: Optional[FPOptions],
224
+ evaluate: Evaluate,
222
225
  ) -> Optional[MatcherResult]:
223
226
  keys = list(node.keys())
224
227
 
@@ -238,7 +241,7 @@ def process_for_block(
238
241
  if len(keys) > 1:
239
242
  raise FPMLValidationError("For block must be presented as single key", path)
240
243
 
241
- answers = evaluate_expression(path, resource, expr, context, fp_options)
244
+ answers = evaluate_expression(path, resource, expr, context, evaluate)
242
245
 
243
246
  return {
244
247
  "node": [
@@ -251,7 +254,7 @@ def process_for_block(
251
254
  item_key: answer,
252
255
  **({index_key: index} if index_key else {}),
253
256
  },
254
- fp_options,
257
+ evaluate,
255
258
  )
256
259
  for index, answer in enumerate(answers)
257
260
  ]
@@ -265,7 +268,7 @@ def process_if_block(
265
268
  resource: Resource,
266
269
  node: dict[str, Any],
267
270
  context: Context,
268
- fp_options: Optional[FPOptions],
271
+ evaluate: Evaluate,
269
272
  ) -> Optional[MatcherResult]:
270
273
  keys = list(node.keys())
271
274
 
@@ -293,15 +296,13 @@ def process_if_block(
293
296
  matches = if_regexp.match(if_key)
294
297
  expr = matches.group(1) if matches else ""
295
298
 
296
- answer = evaluate_expression(path, resource, f"iif({expr}, true, false)", context, fp_options)[
297
- 0
298
- ]
299
+ answer = evaluate_expression(path, resource, f"iif({expr}, true, false)", context, evaluate)[0]
299
300
 
300
301
  new_node = (
301
- resolve_template_recur(path, resource, node[if_key], context, fp_options)
302
+ resolve_template_recur(path, resource, node[if_key], context, evaluate)
302
303
  if answer
303
304
  else (
304
- resolve_template_recur(path, resource, node[else_key], context, fp_options)
305
+ resolve_template_recur(path, resource, node[else_key], context, evaluate)
305
306
  if else_key
306
307
  else undefined
307
308
  )
@@ -330,14 +331,14 @@ def process_merge_block(
330
331
  resource: Resource,
331
332
  node: DictNode,
332
333
  context: Context,
333
- fp_options: Optional[FPOptions],
334
+ evaluate: Evaluate,
334
335
  ) -> Optional[MatcherResult]:
335
336
  merge_key = next((k for k in node if re.match(r"{%\s*merge\s*%}", k)), None)
336
337
  if merge_key:
337
338
  merged_node = omit_key(node, merge_key)
338
339
  values = node[merge_key] if isinstance(node[merge_key], list) else [node[merge_key]]
339
340
  for value in values:
340
- result = resolve_template_recur(path, resource, value, context, fp_options)
341
+ result = resolve_template_recur(path, resource, value, context, evaluate)
341
342
  if not isinstance(result, dict) and result is not None and result is not undefined:
342
343
  raise FPMLValidationError("Merge block must contain object", path)
343
344
  if result is not undefined and result is not None:
@@ -351,7 +352,7 @@ def process_assign_block(
351
352
  resource: Resource,
352
353
  node: DictNode,
353
354
  context: Context,
354
- fp_options: Optional[FPOptions],
355
+ evaluate: Evaluate,
355
356
  ) -> tuple[DictNode, Context]:
356
357
  extended_context = context.copy()
357
358
  assign_key = next((k for k in node if re.match(r"{%\s*assign\s*%}", k)), None)
@@ -365,7 +366,7 @@ def process_assign_block(
365
366
  )
366
367
  result = {
367
368
  key: resolve_template_recur(
368
- [*path, key], resource, obj_value, extended_context, fp_options
369
+ [*path, key], resource, obj_value, extended_context, evaluate
369
370
  )
370
371
  for key, obj_value in obj.items()
371
372
  }
@@ -375,7 +376,7 @@ def process_assign_block(
375
376
  obj = node[assign_key]
376
377
  result = {
377
378
  key: resolve_template_recur(
378
- [*path, key], resource, obj_value, extended_context, fp_options
379
+ [*path, key], resource, obj_value, extended_context, evaluate
379
380
  )
380
381
  for key, obj_value in obj.items()
381
382
  }
@@ -392,17 +393,10 @@ def evaluate_expression(
392
393
  resource: Resource,
393
394
  expression: str,
394
395
  context: Context,
395
- fp_options: Optional[FPOptions] = None,
396
+ evaluate: Evaluate,
396
397
  ) -> list[Any]:
397
- cache = (fp_options or {}).get("cache")
398
-
399
398
  try:
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)
399
+ # Copy, so that an evaluator cannot leak into the sibling expressions
400
+ return evaluate(resource, expression, {**context})
407
401
  except Exception as exc:
408
402
  raise FPMLValidationError(f"Cannot evaluate '{expression}': {exc}", path) from exc
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "fpml"
3
- version = "0.3.1"
3
+ version = "2.0.0"
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 = [
@@ -8,10 +8,10 @@ maintainers = [
8
8
  { name = "Ilya Beda", email = "ilya@beda.software" },
9
9
  ]
10
10
  license = { text = "MIT" }
11
- requires-python = ">=3.9"
11
+ requires-python = ">=3.10"
12
12
  keywords = ["fhir", "fhirpath"]
13
13
  dynamic = ["classifiers"]
14
- dependencies = ["fhirpathpy (>=2.0.0,<3.0.0)"]
14
+ dependencies = ["fhirpathpy (>=3.0.1,<4.0.0)", "typing-extensions (>=4.0.0)"]
15
15
 
16
16
  [project.urls]
17
17
  homepage = "https://github.com/beda-software/FHIRPathMappingLanguage/tree/main/python"
@@ -28,7 +28,6 @@ classifiers = [
28
28
  "Operating System :: OS Independent",
29
29
  "Programming Language :: Python",
30
30
  "Programming Language :: Python :: 3",
31
- "Programming Language :: Python :: 3.9",
32
31
  "Programming Language :: Python :: 3.10",
33
32
  "Programming Language :: Python :: 3.11",
34
33
  "Programming Language :: Python :: 3.12",
@@ -38,7 +37,7 @@ classifiers = [
38
37
  readme = ["README.md"]
39
38
 
40
39
  [tool.poetry.dependencies]
41
- python = ">=3.9,<4.0"
40
+ python = ">=3.10,<4.0"
42
41
 
43
42
  [tool.poetry.group.dev.dependencies]
44
43
  ruff = "^0.9.7"
@@ -1,58 +0,0 @@
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,74 +0,0 @@
1
- from typing import TYPE_CHECKING, Any, Callable, Optional, TypedDict, Union
2
-
3
- from typing_extensions import NotRequired
4
-
5
- if TYPE_CHECKING:
6
- from .cache import ExpressionCache
7
-
8
- Resource = dict[str, Any]
9
- Node = Any
10
- DictNode = dict[str, Any]
11
- StrNode = str
12
- Context = dict[str, Any]
13
-
14
- Path = list[Union[str, int]]
15
-
16
-
17
- class Model(TypedDict):
18
- choiceTypePaths: dict[str, list[str]]
19
- pathsDefinedElsewhere: dict[str, str]
20
- type2Parent: dict[str, str]
21
- path2Type: dict[str, str]
22
-
23
-
24
- class UserFnDefinition(TypedDict):
25
- fn: Callable
26
- arity: dict[int, list[str]]
27
- nullable: NotRequired[bool]
28
-
29
-
30
- UserInvocationTable = dict[str, UserFnDefinition]
31
-
32
-
33
- class FPOptions(TypedDict):
34
- """
35
- Optional parameters for controlling FHIRPath evaluation.
36
-
37
- Attributes:
38
- model (Optional[Model]):
39
- An optional "model" data object specific to a domain, e.g. R4.
40
- See https://github.com/beda-software/fhirpath-py?tab=readme-ov-file#using-data-models
41
- userInvocationTable (Optional[UserInvocationTable]):
42
- A table of user-defined functions that
43
- can be used in FHIRPath expressions during template processing.
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.
48
-
49
- See Also:
50
- FHIRPath py Documentation:
51
- https://github.com/beda-software/fhirpath-py?tab=readme-ov-file#fhirpathpy
52
- """
53
-
54
- model: NotRequired[Model]
55
- userInvocationTable: NotRequired[UserInvocationTable]
56
- cache: NotRequired["ExpressionCache"]
57
-
58
-
59
- class MatcherResult(TypedDict):
60
- node: Optional[Node]
61
-
62
-
63
- Matcher = Callable[
64
- [
65
- Path,
66
- Resource,
67
- DictNode,
68
- Context,
69
- Optional[FPOptions],
70
- ],
71
- Optional[MatcherResult],
72
- ]
73
-
74
- Transformer = Callable[[Path, Node, Context], tuple[Node, Context]]
File without changes
File without changes
File without changes
File without changes
File without changes