flpit 0.5.0__tar.gz → 0.5.2.dev1__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.
- {flpit-0.5.0 → flpit-0.5.2.dev1}/PKG-INFO +18 -16
- {flpit-0.5.0 → flpit-0.5.2.dev1}/README.md +13 -12
- flpit-0.5.2.dev1/THIRD-PARTY-NOTICES.md +33 -0
- {flpit-0.5.0 → flpit-0.5.2.dev1}/pyproject.toml +5 -4
- {flpit-0.5.0 → flpit-0.5.2.dev1}/src/flpit/asyncio_bridge.py +22 -1
- {flpit-0.5.0 → flpit-0.5.2.dev1}/src/flpit/json/_core.py +34 -4
- {flpit-0.5.0 → flpit-0.5.2.dev1}/src/flpit/json/_msgspec.py +58 -1
- {flpit-0.5.0 → flpit-0.5.2.dev1}/src/flpit/json/_native.py +21 -6
- {flpit-0.5.0 → flpit-0.5.2.dev1}/.gitignore +0 -0
- {flpit-0.5.0 → flpit-0.5.2.dev1}/LICENSE +0 -0
- {flpit-0.5.0 → flpit-0.5.2.dev1}/src/flp/__init__.py +0 -0
- {flpit-0.5.0 → flpit-0.5.2.dev1}/src/flpit/__init__.py +0 -0
- {flpit-0.5.0 → flpit-0.5.2.dev1}/src/flpit/channels.py +0 -0
- {flpit-0.5.0 → flpit-0.5.2.dev1}/src/flpit/concurrent.py +0 -0
- {flpit-0.5.0 → flpit-0.5.2.dev1}/src/flpit/core/__init__.py +0 -0
- {flpit-0.5.0 → flpit-0.5.2.dev1}/src/flpit/core/_grouping.py +0 -0
- {flpit-0.5.0 → flpit-0.5.2.dev1}/src/flpit/core/_index.py +0 -0
- {flpit-0.5.0 → flpit-0.5.2.dev1}/src/flpit/core/_join.py +0 -0
- {flpit-0.5.0 → flpit-0.5.2.dev1}/src/flpit/core/_lookup.py +0 -0
- {flpit-0.5.0 → flpit-0.5.2.dev1}/src/flpit/core/_zip.py +0 -0
- {flpit-0.5.0 → flpit-0.5.2.dev1}/src/flpit/core/async_linq.py +0 -0
- {flpit-0.5.0 → flpit-0.5.2.dev1}/src/flpit/core/comparers.py +0 -0
- {flpit-0.5.0 → flpit-0.5.2.dev1}/src/flpit/core/linq.py +0 -0
- {flpit-0.5.0 → flpit-0.5.2.dev1}/src/flpit/csv.py +0 -0
- {flpit-0.5.0 → flpit-0.5.2.dev1}/src/flpit/flp.py +0 -0
- {flpit-0.5.0 → flpit-0.5.2.dev1}/src/flpit/json/__init__.py +0 -0
- {flpit-0.5.0 → flpit-0.5.2.dev1}/src/flpit/py.typed +0 -0
- {flpit-0.5.0 → flpit-0.5.2.dev1}/src/flpit/task.py +0 -0
- {flpit-0.5.0 → flpit-0.5.2.dev1}/src/flpit/threading.py +0 -0
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: flpit
|
|
3
|
-
Version: 0.5.
|
|
4
|
-
Summary:
|
|
3
|
+
Version: 0.5.2.dev1
|
|
4
|
+
Summary: Python that feels like .NET, until you miss the real thing.
|
|
5
5
|
Project-URL: Homepage, https://github.com/riemar/flpit
|
|
6
6
|
Project-URL: Documentation, https://riemar.github.io/flpit/
|
|
7
7
|
Project-URL: Changelog, https://riemar.github.io/flpit/changelog/
|
|
8
8
|
Project-URL: Repository, https://github.com/riemar/flpit
|
|
9
9
|
Project-URL: Issues, https://github.com/riemar/flpit/issues
|
|
10
|
-
License: MIT
|
|
10
|
+
License-Expression: MIT
|
|
11
11
|
License-File: LICENSE
|
|
12
|
-
|
|
12
|
+
License-File: THIRD-PARTY-NOTICES.md
|
|
13
|
+
Keywords: async,async-enumerable,asyncio,cancellation,channels,concurrency,csharp,csv,dotnet,fluent,free-threaded,generators,iterable,json,lazy-evaluation,linq,pipeline,pyrefly,task,threadpool,tpl,type-safe
|
|
13
14
|
Classifier: Development Status :: 4 - Beta
|
|
14
15
|
Classifier: Intended Audience :: Developers
|
|
15
16
|
Classifier: License :: OSI Approved :: MIT License
|
|
@@ -31,22 +32,22 @@ Description-Content-Type: text/markdown
|
|
|
31
32
|
|
|
32
33
|
# FlpIt
|
|
33
34
|
|
|
34
|
-
|
|
35
|
+
*Python that feels like .NET, until you miss the real thing.*
|
|
35
36
|
|
|
36
|
-
|
|
37
|
+
**[📖 Documentation](https://riemar.github.io/flpit/)** | **[🌐 GitHub](https://github.com/riemar/flpit)** | **[📦 PyPI](https://pypi.org/project/flpit/)**
|
|
37
38
|
|
|
38
|
-
|
|
39
|
+
> **The .NET programming model for Python: LINQ, Tasks, async streams and channels, with .NET's semantics.**
|
|
39
40
|
|
|
40
|
-
|
|
41
|
+
`FlpIt` brings .NET's programming model to Python, verified against more than 10,000 unit tests migrated from the .NET runtime.
|
|
42
|
+
Queries come with LINQ's operators and semantics over standard Python iterables. Around them come async streams (`AsyncFlpIt`),
|
|
43
|
+
an `asyncio`-free task runtime, channels, concurrent collections, and typed JSON and CSV serialization.
|
|
44
|
+
It is built for free-threaded Python and tested on 3.12 to 3.15t in CI.
|
|
41
45
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
tested on free-threaded Python (>=3.14t) in CI.
|
|
46
|
+
If you know C#, you already know most of FlpIt. Existing LINQ and TPL examples, query patterns and documentation can generally be translated directly,
|
|
47
|
+
which makes the .NET ecosystem a valuable reference for developers and AI coding assistants alike.
|
|
45
48
|
|
|
46
|
-
> **Semantic goal:**
|
|
47
|
-
>
|
|
48
|
-
> and [each deviation is documented](https://riemar.github.io/flpit/semantics/differences/).
|
|
49
|
-
> The implementation is actively developed, and further deviations may still exist.
|
|
49
|
+
> **Semantic goal:** FlpIt reproduces .NET's semantics, checked by the migrated .NET tests,
|
|
50
|
+
> and [each known deviation is documented](https://riemar.github.io/flpit/semantics/differences/).
|
|
50
51
|
|
|
51
52
|
## 💡 Quick Start
|
|
52
53
|
|
|
@@ -122,7 +123,8 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
122
123
|
|
|
123
124
|
## Migrated .NET Unit Tests
|
|
124
125
|
|
|
125
|
-
|
|
126
|
+
More than 10,000 test cases from the official .NET runtime test suites, migrated to Python and run on every commit against 6 interpreters, each on Linux, Windows and macOS.
|
|
127
|
+
|
|
126
128
|
> Note: The test cases exercise both core types, `FlpIt` and `FlpList`, with transitions between lazy and eager execution occurring as part of the individual test cases.
|
|
127
129
|
> `async_linq/` is migrated from the .NET 10 `System.Linq.AsyncEnumerable` tests and exercises `AsyncFlpIt` on the flpit task runtime.
|
|
128
130
|
> `channels/` is migrated from the `System.Threading.Channels` tests; `concurrent/` from the `System.Collections.Concurrent` tests, including the shared `IEnumerable` / `ICollection` / `IDictionary` suites of `Common/tests` (ported to `common/`).
|
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
# FlpIt
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
*Python that feels like .NET, until you miss the real thing.*
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
**[📖 Documentation](https://riemar.github.io/flpit/)** | **[🌐 GitHub](https://github.com/riemar/flpit)** | **[📦 PyPI](https://pypi.org/project/flpit/)**
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
> **The .NET programming model for Python: LINQ, Tasks, async streams and channels, with .NET's semantics.**
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
`FlpIt` brings .NET's programming model to Python, verified against more than 10,000 unit tests migrated from the .NET runtime.
|
|
10
|
+
Queries come with LINQ's operators and semantics over standard Python iterables. Around them come async streams (`AsyncFlpIt`),
|
|
11
|
+
an `asyncio`-free task runtime, channels, concurrent collections, and typed JSON and CSV serialization.
|
|
12
|
+
It is built for free-threaded Python and tested on 3.12 to 3.15t in CI.
|
|
10
13
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
tested on free-threaded Python (>=3.14t) in CI.
|
|
14
|
+
If you know C#, you already know most of FlpIt. Existing LINQ and TPL examples, query patterns and documentation can generally be translated directly,
|
|
15
|
+
which makes the .NET ecosystem a valuable reference for developers and AI coding assistants alike.
|
|
14
16
|
|
|
15
|
-
> **Semantic goal:**
|
|
16
|
-
>
|
|
17
|
-
> and [each deviation is documented](https://riemar.github.io/flpit/semantics/differences/).
|
|
18
|
-
> The implementation is actively developed, and further deviations may still exist.
|
|
17
|
+
> **Semantic goal:** FlpIt reproduces .NET's semantics, checked by the migrated .NET tests,
|
|
18
|
+
> and [each known deviation is documented](https://riemar.github.io/flpit/semantics/differences/).
|
|
19
19
|
|
|
20
20
|
## 💡 Quick Start
|
|
21
21
|
|
|
@@ -91,7 +91,8 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
91
91
|
|
|
92
92
|
## Migrated .NET Unit Tests
|
|
93
93
|
|
|
94
|
-
|
|
94
|
+
More than 10,000 test cases from the official .NET runtime test suites, migrated to Python and run on every commit against 6 interpreters, each on Linux, Windows and macOS.
|
|
95
|
+
|
|
95
96
|
> Note: The test cases exercise both core types, `FlpIt` and `FlpList`, with transitions between lazy and eager execution occurring as part of the individual test cases.
|
|
96
97
|
> `async_linq/` is migrated from the .NET 10 `System.Linq.AsyncEnumerable` tests and exercises `AsyncFlpIt` on the flpit task runtime.
|
|
97
98
|
> `channels/` is migrated from the `System.Threading.Channels` tests; `concurrent/` from the `System.Collections.Concurrent` tests, including the shared `IEnumerable` / `ICollection` / `IDictionary` suites of `Common/tests` (ported to `common/`).
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# Third-party notices
|
|
2
|
+
|
|
3
|
+
flpit includes code from the projects below, used under their licenses.
|
|
4
|
+
|
|
5
|
+
## dotnet/runtime
|
|
6
|
+
|
|
7
|
+
https://github.com/dotnet/runtime
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
The MIT License (MIT)
|
|
11
|
+
|
|
12
|
+
Copyright (c) .NET Foundation and Contributors
|
|
13
|
+
|
|
14
|
+
All rights reserved.
|
|
15
|
+
|
|
16
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
17
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
18
|
+
in the Software without restriction, including without limitation the rights
|
|
19
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
20
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
21
|
+
furnished to do so, subject to the following conditions:
|
|
22
|
+
|
|
23
|
+
The above copyright notice and this permission notice shall be included in all
|
|
24
|
+
copies or substantial portions of the Software.
|
|
25
|
+
|
|
26
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
27
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
28
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
29
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
30
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
31
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
32
|
+
SOFTWARE.
|
|
33
|
+
```
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "flpit"
|
|
3
|
-
version = "0.5.
|
|
4
|
-
description = "
|
|
3
|
+
version = "0.5.2.dev1"
|
|
4
|
+
description = "Python that feels like .NET, until you miss the real thing."
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
requires-python = ">=3.12"
|
|
7
|
-
license =
|
|
8
|
-
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE", "THIRD-PARTY-NOTICES.md"]
|
|
9
|
+
keywords = ["linq", "dotnet", "csharp", "fluent", "iterable", "pipeline", "lazy-evaluation", "generators", "async", "async-enumerable", "asyncio", "task", "tpl", "cancellation", "threadpool", "concurrency", "channels", "free-threaded", "json", "csv", "type-safe", "pyrefly"]
|
|
9
10
|
classifiers = [
|
|
10
11
|
"Development Status :: 4 - Beta",
|
|
11
12
|
"Intended Audience :: Developers",
|
|
@@ -547,6 +547,26 @@ async def _await(awaitable: Awaitable[T]) -> T:
|
|
|
547
547
|
return await awaitable
|
|
548
548
|
|
|
549
549
|
|
|
550
|
+
_RUNNING: Final = "_flpit_running_tasks"
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def _keep_until_done(loop: asyncio.AbstractEventLoop, task: asyncio.Task[Any]) -> None:
|
|
554
|
+
"""Hold ``task`` strongly until it is done.
|
|
555
|
+
|
|
556
|
+
asyncio keeps only weak references to tasks, and an awaited stream read is reachable from
|
|
557
|
+
the loop only weakly too (``StreamReaderProtocol`` holds its reader by weakref). Without this,
|
|
558
|
+
a cyclic GC run while the task waits destroys it ("Task was destroyed but it is pending!")
|
|
559
|
+
and the caller waits forever. The set lives on the loop: the reference goes when the task
|
|
560
|
+
is done, or with the loop.
|
|
561
|
+
"""
|
|
562
|
+
running: set[asyncio.Task[Any]] | None = getattr(loop, _RUNNING, None)
|
|
563
|
+
if running is None:
|
|
564
|
+
running = set()
|
|
565
|
+
setattr(loop, _RUNNING, running)
|
|
566
|
+
running.add(task)
|
|
567
|
+
task.add_done_callback(running.discard)
|
|
568
|
+
|
|
569
|
+
|
|
550
570
|
class _Run:
|
|
551
571
|
"""One asyncio task started for run_asyncio: its token registration and completion."""
|
|
552
572
|
|
|
@@ -610,6 +630,7 @@ def _start(loop: asyncio.AbstractEventLoop, pool: _LoopPool | None, coroutine: C
|
|
|
610
630
|
else:
|
|
611
631
|
coroutine = _after_gate(gate, coroutine)
|
|
612
632
|
task = loop.create_task(coroutine, context=context)
|
|
633
|
+
_keep_until_done(loop, task)
|
|
613
634
|
run.task = task
|
|
614
635
|
task.add_done_callback(run.finish)
|
|
615
636
|
if run.cancel_requested:
|
|
@@ -848,7 +869,7 @@ class PerLoop(LoopLocal[T]):
|
|
|
848
869
|
if loop.is_closed():
|
|
849
870
|
continue
|
|
850
871
|
if loop is running:
|
|
851
|
-
loop.create_task(_close_value(value)) # cannot wait for our own loop
|
|
872
|
+
_keep_until_done(loop, loop.create_task(_close_value(value))) # cannot wait for our own loop
|
|
852
873
|
continue
|
|
853
874
|
try:
|
|
854
875
|
pending.append(asyncio.run_coroutine_threadsafe(_close_value(value), loop))
|
|
@@ -9,7 +9,7 @@ import dataclasses
|
|
|
9
9
|
import re
|
|
10
10
|
import threading
|
|
11
11
|
import typing
|
|
12
|
-
from collections.abc import Callable
|
|
12
|
+
from collections.abc import Callable, Iterable
|
|
13
13
|
from dataclasses import dataclass
|
|
14
14
|
from enum import StrEnum
|
|
15
15
|
from hashlib import blake2s
|
|
@@ -82,14 +82,37 @@ class JPropMeta(type):
|
|
|
82
82
|
return SpecializedJProp
|
|
83
83
|
|
|
84
84
|
class JProp:
|
|
85
|
-
|
|
86
|
-
json_name: str
|
|
85
|
+
"""Sets a field's JSON name; ``aliases`` are further names accepted when reading.
|
|
87
86
|
|
|
88
|
-
|
|
87
|
+
``JProp("page_size", aliases=("limit",))`` reads ``page_size`` or ``limit`` and always
|
|
88
|
+
writes ``page_size``. The name and the aliases are exact JSON names: the naming policy
|
|
89
|
+
doesn't apply to them. Without a name (``JProp(aliases=("limit",))``) the field keeps
|
|
90
|
+
the name the naming policy gives it. When a JSON object has several of them, the
|
|
91
|
+
field's own name wins, then the aliases in the order given.
|
|
92
|
+
"""
|
|
93
|
+
|
|
94
|
+
__slots__ = ("json_name", "aliases")
|
|
95
|
+
json_name: str | None
|
|
96
|
+
aliases: tuple[str, ...]
|
|
97
|
+
|
|
98
|
+
def __init__(self, json_name: str | None = None, *, aliases: Iterable[str] = ()):
|
|
99
|
+
if isinstance(aliases, str):
|
|
100
|
+
raise TypeError("aliases must be a sequence of names, not a single string")
|
|
101
|
+
names = tuple(aliases)
|
|
102
|
+
if json_name is None and not names:
|
|
103
|
+
raise TypeError("JProp needs a JSON name, aliases, or both")
|
|
104
|
+
for name in names:
|
|
105
|
+
if not isinstance(name, str) or not name:
|
|
106
|
+
raise TypeError(f"aliases must be non-empty strings, got {name!r}")
|
|
107
|
+
if len(set(names)) != len(names) or (json_name is not None and json_name in names):
|
|
108
|
+
raise ValueError(f"duplicate JSON name in JProp({json_name!r}, aliases={names!r})")
|
|
89
109
|
self.json_name = json_name
|
|
110
|
+
self.aliases = names
|
|
90
111
|
|
|
91
112
|
# 1. This handles the standard initialization/metadata if needed
|
|
92
113
|
def __repr__(self):
|
|
114
|
+
if self.aliases:
|
|
115
|
+
return f"JProp(json_name={self.json_name!r}, aliases={self.aliases!r})"
|
|
93
116
|
return f"JProp(json_name={self.json_name!r})"
|
|
94
117
|
|
|
95
118
|
# 2. This intercepts JProp[str] (the type subscription first)
|
|
@@ -209,6 +232,13 @@ def _field_directives(
|
|
|
209
232
|
return base_type, ignored, included, json_name
|
|
210
233
|
|
|
211
234
|
|
|
235
|
+
def _field_aliases(annotation: Any) -> tuple[str, ...]:
|
|
236
|
+
"""The aliases of a field's ``JProp`` (names accepted when reading), or ``()``."""
|
|
237
|
+
if get_origin(annotation) is not typing.Annotated:
|
|
238
|
+
return ()
|
|
239
|
+
return next((item.aliases for item in get_args(annotation)[1:] if isinstance(item, JProp)), ())
|
|
240
|
+
|
|
241
|
+
|
|
212
242
|
def _get_property_directive(prop_func: Callable[[Any, Any], None] | Callable[[Any], Any] | None):
|
|
213
243
|
if prop_func is not None:
|
|
214
244
|
getter_hints = get_type_hints(prop_func, include_extras=True)
|
|
@@ -29,6 +29,7 @@ from flpit.json._core import (
|
|
|
29
29
|
JsonUnknownFieldHandling,
|
|
30
30
|
_allows_none,
|
|
31
31
|
_apply_naming_policy,
|
|
32
|
+
_field_aliases,
|
|
32
33
|
_field_directives,
|
|
33
34
|
_get_property_directive,
|
|
34
35
|
_is_dataclass_type,
|
|
@@ -58,6 +59,8 @@ class _WireType:
|
|
|
58
59
|
""""decode" structs hold registered collections as plain lists (decoded natively),
|
|
59
60
|
"encode" structs as _WireCollection (filled from FlpList & co. through the hook)."""
|
|
60
61
|
struct: type | None = None
|
|
62
|
+
aliased: list[tuple[str, tuple[str, ...], str, Any, Any, bool]] = dataclasses.field(default_factory=list)
|
|
63
|
+
"""Decode mode: (field, alias attributes, JSON name, default, default factory, implicit None) per aliased field."""
|
|
61
64
|
|
|
62
65
|
@property
|
|
63
66
|
def module_name(self: _WireType) -> str:
|
|
@@ -249,6 +252,21 @@ def _struct_fields(
|
|
|
249
252
|
else:
|
|
250
253
|
field_options["default"] = default_val
|
|
251
254
|
|
|
255
|
+
aliases = _field_aliases(source_annotation)
|
|
256
|
+
if aliases and info.mode == "decode":
|
|
257
|
+
# msgspec has no aliases: each one is a hidden field of its own, and the struct's
|
|
258
|
+
# __post_init__ resolves them. The field itself starts UNSET to tell "absent" apart.
|
|
259
|
+
attributes = tuple(f"_flpit_alias_{field.name}_{i}" for i in range(len(aliases)))
|
|
260
|
+
definitions.append((field.name, annotation, msgspec.field(name=wire_name, default=msgspec.UNSET)))
|
|
261
|
+
for attribute, alias in zip(attributes, aliases):
|
|
262
|
+
definitions.append((attribute, annotation, msgspec.field(name=alias, default=msgspec.UNSET)))
|
|
263
|
+
info.aliased.append((
|
|
264
|
+
field.name, attributes, wire_name,
|
|
265
|
+
field.default, field.default_factory,
|
|
266
|
+
field.default is MISSING and field.default_factory is MISSING and _allows_none(annotation),
|
|
267
|
+
))
|
|
268
|
+
continue
|
|
269
|
+
|
|
252
270
|
spec = (field.name, annotation, msgspec.field(**field_options))
|
|
253
271
|
definitions.append(spec)
|
|
254
272
|
|
|
@@ -271,6 +289,8 @@ def _struct_fields(
|
|
|
271
289
|
|
|
272
290
|
if not included and json_name is None:
|
|
273
291
|
continue
|
|
292
|
+
if _field_aliases(get_type_hints(value.fget, include_extras=True).get("return")):
|
|
293
|
+
raise ValueError(f"{info.source.__qualname__}.{name}: JProp aliases are only supported on fields")
|
|
274
294
|
|
|
275
295
|
annotation = _rewrite_type(annotation, info, graph)
|
|
276
296
|
wire_name = json_name if json_name is not None else _apply_naming_policy(name, jso.naming_policy)
|
|
@@ -317,11 +337,15 @@ def _create_structs(
|
|
|
317
337
|
"""Create the generated msgspec structs for every node in the graph."""
|
|
318
338
|
for wt in graph.values():
|
|
319
339
|
fields = _struct_fields(wt, graph, jso)
|
|
340
|
+
_check_wire_names(wt.source, fields)
|
|
341
|
+
namespace = _behavior_namespace(wt.source)
|
|
342
|
+
if wt.aliased:
|
|
343
|
+
namespace["__post_init__"] = _resolve_aliases(wt.aliased)
|
|
320
344
|
wt.struct = msgspec.defstruct(
|
|
321
345
|
wt.class_name,
|
|
322
346
|
fields,
|
|
323
347
|
module=wt.module_name,
|
|
324
|
-
namespace=
|
|
348
|
+
namespace=namespace,
|
|
325
349
|
rename=None,
|
|
326
350
|
kw_only=True, # optional fields may precede required ones (dataclass order)
|
|
327
351
|
omit_defaults=jso.default_handling.value == JsonDefaultHandling.exclude,
|
|
@@ -329,6 +353,39 @@ def _create_structs(
|
|
|
329
353
|
)
|
|
330
354
|
|
|
331
355
|
|
|
356
|
+
def _check_wire_names(source: type, fields: list[tuple[Any, ...]]) -> None:
|
|
357
|
+
seen: dict[str, str] = {}
|
|
358
|
+
for attribute, _, options in fields:
|
|
359
|
+
wire = options.name if options.name is not None else attribute
|
|
360
|
+
owner = attribute.split("_flpit_alias_", 1)[1].rsplit("_", 1)[0] if attribute.startswith("_flpit_alias_") else attribute
|
|
361
|
+
if wire in seen and seen[wire] != owner:
|
|
362
|
+
raise ValueError(f"{source.__qualname__}: '{owner}' and '{seen[wire]}' both map to JSON name '{wire}'")
|
|
363
|
+
seen.setdefault(wire, owner)
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def _resolve_aliases(aliased: list[tuple[str, tuple[str, ...], str, Any, Any, bool]]) -> Any:
|
|
367
|
+
unset = msgspec.UNSET
|
|
368
|
+
|
|
369
|
+
def __post_init__(self: Any) -> None:
|
|
370
|
+
for name, attributes, wire, default, factory, implicit_none in aliased:
|
|
371
|
+
if getattr(self, name) is unset:
|
|
372
|
+
value = next((getattr(self, a) for a in attributes if getattr(self, a) is not unset), unset)
|
|
373
|
+
if value is unset:
|
|
374
|
+
if default is not MISSING:
|
|
375
|
+
value = default
|
|
376
|
+
elif factory is not MISSING:
|
|
377
|
+
value = factory()
|
|
378
|
+
elif implicit_none:
|
|
379
|
+
value = None
|
|
380
|
+
else:
|
|
381
|
+
raise ValueError(f"Object missing required field `{wire}`")
|
|
382
|
+
setattr(self, name, value)
|
|
383
|
+
for attribute in attributes:
|
|
384
|
+
setattr(self, attribute, unset)
|
|
385
|
+
|
|
386
|
+
return __post_init__
|
|
387
|
+
|
|
388
|
+
|
|
332
389
|
def _validate_structs(graph: dict[type, _WireType]) -> None:
|
|
333
390
|
"""Force msgspec to inspect each generated struct after refs are registered."""
|
|
334
391
|
for wt in graph.values():
|
|
@@ -37,6 +37,7 @@ from flpit.json._core import (
|
|
|
37
37
|
JsonUnknownFieldHandling,
|
|
38
38
|
_allows_none,
|
|
39
39
|
_apply_naming_policy,
|
|
40
|
+
_field_aliases,
|
|
40
41
|
_field_directives,
|
|
41
42
|
_get_property_directive,
|
|
42
43
|
_nested_dataclasses,
|
|
@@ -229,6 +230,7 @@ class _FieldSpec:
|
|
|
229
230
|
default: Any # MISSING when none
|
|
230
231
|
default_factory: Any # MISSING when none
|
|
231
232
|
implicit_none: bool # optional without default -> None
|
|
233
|
+
aliases: tuple[str, ...] = () # further names accepted when reading
|
|
232
234
|
|
|
233
235
|
|
|
234
236
|
@dataclasses.dataclass(slots=True)
|
|
@@ -257,6 +259,9 @@ def _class_layout(cls: type, jso: JsonSerializerOptions) -> tuple[list[_FieldSpe
|
|
|
257
259
|
continue
|
|
258
260
|
wire = json_name if json_name is not None else _apply_naming_policy(field.name, jso.naming_policy)
|
|
259
261
|
claim(wire, field.name)
|
|
262
|
+
aliases = _field_aliases(hints[field.name])
|
|
263
|
+
for alias in aliases:
|
|
264
|
+
claim(alias, field.name)
|
|
260
265
|
fields.append(_FieldSpec(
|
|
261
266
|
name=field.name,
|
|
262
267
|
wire=wire,
|
|
@@ -266,6 +271,7 @@ def _class_layout(cls: type, jso: JsonSerializerOptions) -> tuple[list[_FieldSpe
|
|
|
266
271
|
default_factory=field.default_factory,
|
|
267
272
|
implicit_none=(field.default is MISSING and field.default_factory is MISSING
|
|
268
273
|
and _allows_none(annotation)),
|
|
274
|
+
aliases=aliases,
|
|
269
275
|
))
|
|
270
276
|
|
|
271
277
|
field_names = {f.name for f in dataclasses.fields(cls)}
|
|
@@ -281,6 +287,8 @@ def _class_layout(cls: type, jso: JsonSerializerOptions) -> tuple[list[_FieldSpe
|
|
|
281
287
|
annotation, _, included, json_name = _get_property_directive(value.fget)
|
|
282
288
|
if not included and json_name is None:
|
|
283
289
|
continue
|
|
290
|
+
if _property_aliases(value.fget):
|
|
291
|
+
raise ValueError(f"{cls.__qualname__}.{name}: JProp aliases are only supported on fields")
|
|
284
292
|
wire = json_name if json_name is not None else _apply_naming_policy(name, jso.naming_policy)
|
|
285
293
|
claim(wire, name)
|
|
286
294
|
properties.append(_PropertySpec(name, wire, annotation))
|
|
@@ -288,6 +296,10 @@ def _class_layout(cls: type, jso: JsonSerializerOptions) -> tuple[list[_FieldSpe
|
|
|
288
296
|
return fields, properties
|
|
289
297
|
|
|
290
298
|
|
|
299
|
+
def _property_aliases(getter: Any) -> tuple[str, ...]:
|
|
300
|
+
return _field_aliases(get_type_hints(getter, include_extras=True).get("return"))
|
|
301
|
+
|
|
302
|
+
|
|
291
303
|
def _strip_annotated(tp: Any) -> Any:
|
|
292
304
|
while get_origin(tp) is typing.Annotated:
|
|
293
305
|
tp = get_args(tp)[0]
|
|
@@ -586,9 +598,9 @@ class _DecoderBuilder:
|
|
|
586
598
|
def _dataclass(self, cls: type) -> Converter:
|
|
587
599
|
fields, properties = _class_layout(cls, self.jso)
|
|
588
600
|
forbid = self.jso.unknown_field_handling == JsonUnknownFieldHandling.disallow
|
|
589
|
-
known = {f.wire for f in fields} | {p.wire for p in properties}
|
|
601
|
+
known = {f.wire for f in fields} | {a for f in fields for a in f.aliases} | {p.wire for p in properties}
|
|
590
602
|
plan = [
|
|
591
|
-
(f.name, f.wire, self.build(f.annotation),
|
|
603
|
+
(f.name, f.wire, f.aliases, self.build(f.annotation),
|
|
592
604
|
f.default is MISSING and f.default_factory is MISSING and not f.implicit_none,
|
|
593
605
|
f.implicit_none, f.init)
|
|
594
606
|
for f in fields
|
|
@@ -604,12 +616,15 @@ class _DecoderBuilder:
|
|
|
604
616
|
raise _Invalid(f"Object contains unknown field `{k}`")
|
|
605
617
|
kwargs: dict[str, Any] = {}
|
|
606
618
|
late: list[tuple[str, Any]] = []
|
|
607
|
-
for name, wire, decode, required, implicit_none, init in plan:
|
|
608
|
-
|
|
619
|
+
for name, wire, aliases, decode, required, implicit_none, init in plan:
|
|
620
|
+
key = wire
|
|
621
|
+
if wire not in v and aliases:
|
|
622
|
+
key = next((alias for alias in aliases if alias in v), wire)
|
|
623
|
+
if key in v:
|
|
609
624
|
try:
|
|
610
|
-
value = decode(v[
|
|
625
|
+
value = decode(v[key])
|
|
611
626
|
except _Invalid as exc:
|
|
612
|
-
raise exc.at(
|
|
627
|
+
raise exc.at(key) from None
|
|
613
628
|
elif required:
|
|
614
629
|
raise _Invalid(f"Object missing required field `{wire}`")
|
|
615
630
|
elif implicit_none:
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|