flpit 0.5.1__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.
Files changed (29) hide show
  1. {flpit-0.5.1 → flpit-0.5.2.dev1}/PKG-INFO +1 -1
  2. {flpit-0.5.1 → flpit-0.5.2.dev1}/pyproject.toml +1 -1
  3. {flpit-0.5.1 → flpit-0.5.2.dev1}/src/flpit/asyncio_bridge.py +22 -1
  4. {flpit-0.5.1 → flpit-0.5.2.dev1}/src/flpit/json/_core.py +34 -4
  5. {flpit-0.5.1 → flpit-0.5.2.dev1}/src/flpit/json/_msgspec.py +58 -1
  6. {flpit-0.5.1 → flpit-0.5.2.dev1}/src/flpit/json/_native.py +21 -6
  7. {flpit-0.5.1 → flpit-0.5.2.dev1}/.gitignore +0 -0
  8. {flpit-0.5.1 → flpit-0.5.2.dev1}/LICENSE +0 -0
  9. {flpit-0.5.1 → flpit-0.5.2.dev1}/README.md +0 -0
  10. {flpit-0.5.1 → flpit-0.5.2.dev1}/THIRD-PARTY-NOTICES.md +0 -0
  11. {flpit-0.5.1 → flpit-0.5.2.dev1}/src/flp/__init__.py +0 -0
  12. {flpit-0.5.1 → flpit-0.5.2.dev1}/src/flpit/__init__.py +0 -0
  13. {flpit-0.5.1 → flpit-0.5.2.dev1}/src/flpit/channels.py +0 -0
  14. {flpit-0.5.1 → flpit-0.5.2.dev1}/src/flpit/concurrent.py +0 -0
  15. {flpit-0.5.1 → flpit-0.5.2.dev1}/src/flpit/core/__init__.py +0 -0
  16. {flpit-0.5.1 → flpit-0.5.2.dev1}/src/flpit/core/_grouping.py +0 -0
  17. {flpit-0.5.1 → flpit-0.5.2.dev1}/src/flpit/core/_index.py +0 -0
  18. {flpit-0.5.1 → flpit-0.5.2.dev1}/src/flpit/core/_join.py +0 -0
  19. {flpit-0.5.1 → flpit-0.5.2.dev1}/src/flpit/core/_lookup.py +0 -0
  20. {flpit-0.5.1 → flpit-0.5.2.dev1}/src/flpit/core/_zip.py +0 -0
  21. {flpit-0.5.1 → flpit-0.5.2.dev1}/src/flpit/core/async_linq.py +0 -0
  22. {flpit-0.5.1 → flpit-0.5.2.dev1}/src/flpit/core/comparers.py +0 -0
  23. {flpit-0.5.1 → flpit-0.5.2.dev1}/src/flpit/core/linq.py +0 -0
  24. {flpit-0.5.1 → flpit-0.5.2.dev1}/src/flpit/csv.py +0 -0
  25. {flpit-0.5.1 → flpit-0.5.2.dev1}/src/flpit/flp.py +0 -0
  26. {flpit-0.5.1 → flpit-0.5.2.dev1}/src/flpit/json/__init__.py +0 -0
  27. {flpit-0.5.1 → flpit-0.5.2.dev1}/src/flpit/py.typed +0 -0
  28. {flpit-0.5.1 → flpit-0.5.2.dev1}/src/flpit/task.py +0 -0
  29. {flpit-0.5.1 → flpit-0.5.2.dev1}/src/flpit/threading.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: flpit
3
- Version: 0.5.1
3
+ Version: 0.5.2.dev1
4
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/
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "flpit"
3
- version = "0.5.1"
3
+ version = "0.5.2.dev1"
4
4
  description = "Python that feels like .NET, until you miss the real thing."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
@@ -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
- __slots__ = ("json_name",)
86
- json_name: str
85
+ """Sets a field's JSON name; ``aliases`` are further names accepted when reading.
87
86
 
88
- def __init__(self, json_name: str):
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=_behavior_namespace(wt.source),
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
- if wire in v:
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[wire])
625
+ value = decode(v[key])
611
626
  except _Invalid as exc:
612
- raise exc.at(wire) from None
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