json-structure 0.1.6__py3-none-any.whl

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.
@@ -0,0 +1,561 @@
1
+ """
2
+ JSON Structure Schema Exporter for Python.
3
+
4
+ Generates JSON Structure schemas from Python dataclasses, similar to
5
+ JsonStructureSchemaExporter in .NET.
6
+ """
7
+
8
+ import dataclasses
9
+ import enum
10
+ import inspect
11
+ import re
12
+ import sys
13
+ from datetime import date, datetime, time, timedelta
14
+ from decimal import Decimal
15
+ from typing import (
16
+ Any, Callable, Dict, FrozenSet, Generic, List, Mapping, Optional,
17
+ Set, Tuple, Type, TypeVar, Union, get_args, get_origin, get_type_hints
18
+ )
19
+ from uuid import UUID
20
+
21
+ # Python 3.9+ compatibility
22
+ if sys.version_info >= (3, 10):
23
+ from types import UnionType
24
+ else:
25
+ UnionType = None
26
+
27
+
28
+ class SchemaExporterOptions:
29
+ """Options for controlling JSON Structure schema generation."""
30
+
31
+ def __init__(
32
+ self,
33
+ schema_uri: str = "https://json-structure.org/meta/core/v0/#",
34
+ include_schema_keyword: bool = True,
35
+ include_titles: bool = True,
36
+ include_descriptions: bool = True,
37
+ include_defaults: bool = True,
38
+ transform_schema: Optional[Callable[['SchemaExporterContext', dict], dict]] = None
39
+ ):
40
+ """
41
+ Initialize schema exporter options.
42
+
43
+ Args:
44
+ schema_uri: The $schema URI to use. Defaults to JSON Structure 1.0.
45
+ include_schema_keyword: Whether to include $schema. Default True.
46
+ include_titles: Whether to include title from class name. Default True.
47
+ include_descriptions: Whether to include description from docstrings. Default True.
48
+ include_defaults: Whether to include default values. Default True.
49
+ transform_schema: Optional callback to transform generated schemas.
50
+ """
51
+ self.schema_uri = schema_uri
52
+ self.include_schema_keyword = include_schema_keyword
53
+ self.include_titles = include_titles
54
+ self.include_descriptions = include_descriptions
55
+ self.include_defaults = include_defaults
56
+ self.transform_schema = transform_schema
57
+
58
+
59
+ @dataclasses.dataclass
60
+ class SchemaExporterContext:
61
+ """Context provided to schema transformation callbacks."""
62
+
63
+ type_: Type
64
+ """The type being processed."""
65
+
66
+ field: Optional[dataclasses.Field] = None
67
+ """The dataclass field if processing a field."""
68
+
69
+ path: str = ""
70
+ """The path in the schema."""
71
+
72
+ @property
73
+ def is_root(self) -> bool:
74
+ """Returns True if this is the root schema."""
75
+ return not self.path
76
+
77
+
78
+ # Field metadata keys for constraints
79
+ class FieldConstraints:
80
+ """Metadata keys for field constraints."""
81
+
82
+ MIN_LENGTH = "min_length"
83
+ MAX_LENGTH = "max_length"
84
+ MINIMUM = "minimum"
85
+ MAXIMUM = "maximum"
86
+ EXCLUSIVE_MINIMUM = "exclusive_minimum"
87
+ EXCLUSIVE_MAXIMUM = "exclusive_maximum"
88
+ PATTERN = "pattern"
89
+ MULTIPLE_OF = "multiple_of"
90
+ MIN_ITEMS = "min_items"
91
+ MAX_ITEMS = "max_items"
92
+ UNIQUE_ITEMS = "unique_items"
93
+ DEPRECATED = "deprecated"
94
+ TITLE = "title"
95
+ DESCRIPTION = "description"
96
+ EXAMPLES = "examples"
97
+
98
+
99
+ def field_constraints(
100
+ min_length: Optional[int] = None,
101
+ max_length: Optional[int] = None,
102
+ minimum: Optional[float] = None,
103
+ maximum: Optional[float] = None,
104
+ exclusive_minimum: Optional[float] = None,
105
+ exclusive_maximum: Optional[float] = None,
106
+ pattern: Optional[str] = None,
107
+ multiple_of: Optional[float] = None,
108
+ min_items: Optional[int] = None,
109
+ max_items: Optional[int] = None,
110
+ unique_items: Optional[bool] = None,
111
+ deprecated: Optional[bool] = None,
112
+ title: Optional[str] = None,
113
+ description: Optional[str] = None,
114
+ examples: Optional[List[Any]] = None,
115
+ ) -> Dict[str, Any]:
116
+ """
117
+ Create a metadata dictionary for dataclass field constraints.
118
+
119
+ Usage:
120
+ @dataclass
121
+ class Person:
122
+ name: str = field(metadata=field_constraints(min_length=1, max_length=100))
123
+ age: int = field(metadata=field_constraints(minimum=0, maximum=150))
124
+
125
+ Args:
126
+ min_length: Minimum string length.
127
+ max_length: Maximum string length.
128
+ minimum: Minimum numeric value (inclusive).
129
+ maximum: Maximum numeric value (inclusive).
130
+ exclusive_minimum: Minimum numeric value (exclusive).
131
+ exclusive_maximum: Maximum numeric value (exclusive).
132
+ pattern: Regex pattern for strings.
133
+ multiple_of: Number must be multiple of this value.
134
+ min_items: Minimum array length.
135
+ max_items: Maximum array length.
136
+ unique_items: Whether array items must be unique.
137
+ deprecated: Whether the field is deprecated.
138
+ title: Title for the field schema.
139
+ description: Description for the field schema.
140
+ examples: Example values for the field.
141
+
142
+ Returns:
143
+ Metadata dictionary to pass to dataclasses.field(metadata=...).
144
+ """
145
+ result = {}
146
+
147
+ if min_length is not None:
148
+ result[FieldConstraints.MIN_LENGTH] = min_length
149
+ if max_length is not None:
150
+ result[FieldConstraints.MAX_LENGTH] = max_length
151
+ if minimum is not None:
152
+ result[FieldConstraints.MINIMUM] = minimum
153
+ if maximum is not None:
154
+ result[FieldConstraints.MAXIMUM] = maximum
155
+ if exclusive_minimum is not None:
156
+ result[FieldConstraints.EXCLUSIVE_MINIMUM] = exclusive_minimum
157
+ if exclusive_maximum is not None:
158
+ result[FieldConstraints.EXCLUSIVE_MAXIMUM] = exclusive_maximum
159
+ if pattern is not None:
160
+ result[FieldConstraints.PATTERN] = pattern
161
+ if multiple_of is not None:
162
+ result[FieldConstraints.MULTIPLE_OF] = multiple_of
163
+ if min_items is not None:
164
+ result[FieldConstraints.MIN_ITEMS] = min_items
165
+ if max_items is not None:
166
+ result[FieldConstraints.MAX_ITEMS] = max_items
167
+ if unique_items is not None:
168
+ result[FieldConstraints.UNIQUE_ITEMS] = unique_items
169
+ if deprecated is not None:
170
+ result[FieldConstraints.DEPRECATED] = deprecated
171
+ if title is not None:
172
+ result[FieldConstraints.TITLE] = title
173
+ if description is not None:
174
+ result[FieldConstraints.DESCRIPTION] = description
175
+ if examples is not None:
176
+ result[FieldConstraints.EXAMPLES] = examples
177
+
178
+ return result
179
+
180
+
181
+ class JsonStructureSchemaExporter:
182
+ """
183
+ Generates JSON Structure schemas from Python dataclasses.
184
+
185
+ Similar to JsonStructureSchemaExporter in the .NET SDK.
186
+ """
187
+
188
+ # Type mapping from Python types to JSON Structure types
189
+ TYPE_MAP: Dict[Type, str] = {
190
+ str: "string",
191
+ bool: "boolean",
192
+ int: "int64", # Python ints are arbitrary precision, default to int64
193
+ float: "double", # Python floats are 64-bit
194
+ bytes: "binary",
195
+ bytearray: "binary",
196
+ Decimal: "decimal",
197
+ date: "date",
198
+ datetime: "datetime",
199
+ time: "time",
200
+ timedelta: "duration",
201
+ UUID: "uuid",
202
+ }
203
+
204
+ def __init__(self, options: Optional[SchemaExporterOptions] = None):
205
+ """
206
+ Initialize the schema exporter.
207
+
208
+ Args:
209
+ options: Optional exporter options.
210
+ """
211
+ self.options = options or SchemaExporterOptions()
212
+ self._visited_types: Set[Type] = set()
213
+ self._definitions: Dict[str, dict] = {}
214
+
215
+ def export(self, type_: Type) -> dict:
216
+ """
217
+ Export a JSON Structure schema from a Python type.
218
+
219
+ Args:
220
+ type_: The type to generate a schema for. Should be a dataclass.
221
+
222
+ Returns:
223
+ A dictionary representing the JSON Structure schema.
224
+ """
225
+ self._visited_types = set()
226
+ self._definitions = {}
227
+
228
+ schema = self._generate_schema(type_, "", None)
229
+
230
+ # Add $defs if there are any
231
+ if self._definitions:
232
+ schema["$defs"] = self._definitions
233
+
234
+ return schema
235
+
236
+ def _generate_schema(
237
+ self,
238
+ type_: Type,
239
+ path: str,
240
+ field: Optional[dataclasses.Field]
241
+ ) -> dict:
242
+ """Generate schema for a type."""
243
+ schema: Dict[str, Any] = {}
244
+ is_root = not path
245
+
246
+ # Add $schema for root
247
+ if is_root and self.options.include_schema_keyword:
248
+ schema["$schema"] = self.options.schema_uri
249
+
250
+ # Handle Optional types
251
+ origin = get_origin(type_)
252
+ args = get_args(type_)
253
+
254
+ # Check for Optional[T] which is Union[T, None]
255
+ is_optional = False
256
+ if origin is Union or (UnionType and isinstance(type_, UnionType)):
257
+ # Check if it's Optional (Union with None)
258
+ non_none_args = [a for a in args if a is not type(None)]
259
+ if len(non_none_args) == 1 and type(None) in args:
260
+ is_optional = True
261
+ type_ = non_none_args[0]
262
+ origin = get_origin(type_)
263
+ args = get_args(type_)
264
+
265
+ # Check for recursion
266
+ if self._is_complex_type(type_) and type_ in self._visited_types:
267
+ type_name = self._get_type_name(type_)
268
+ return {"$ref": f"#/$defs/{type_name}"}
269
+
270
+ # Map type to JSON Structure type
271
+ structure_type = self._get_json_structure_type(type_)
272
+ if structure_type:
273
+ schema["type"] = structure_type
274
+
275
+ # Handle enums
276
+ if isinstance(type_, type) and issubclass(type_, enum.Enum):
277
+ schema["type"] = "string"
278
+ schema["enum"] = [member.value if isinstance(member.value, str) else member.name
279
+ for member in type_]
280
+ return self._apply_transform(schema, type_, field, path)
281
+
282
+ # Handle collections
283
+ if origin is list or origin is List:
284
+ schema["type"] = "array"
285
+ if args:
286
+ schema["items"] = self._generate_schema(args[0], path + "/items", None)
287
+ return self._apply_transform(schema, type_, field, path)
288
+
289
+ if origin is set or origin is Set or origin is frozenset or origin is FrozenSet:
290
+ schema["type"] = "set"
291
+ if args:
292
+ schema["items"] = self._generate_schema(args[0], path + "/items", None)
293
+ return self._apply_transform(schema, type_, field, path)
294
+
295
+ if origin is dict or origin is Dict or origin is Mapping:
296
+ schema["type"] = "map"
297
+ if args and len(args) >= 2:
298
+ schema["values"] = self._generate_schema(args[1], path + "/values", None)
299
+ return self._apply_transform(schema, type_, field, path)
300
+
301
+ if origin is tuple or origin is Tuple:
302
+ schema["type"] = "tuple"
303
+ if args:
304
+ # Handle Tuple[int, str, ...] - variable length
305
+ if len(args) == 2 and args[1] is ...:
306
+ schema["items"] = self._generate_schema(args[0], path + "/items", None)
307
+ else:
308
+ # Fixed length tuple
309
+ prefix_items = []
310
+ for i, arg in enumerate(args):
311
+ prefix_items.append(
312
+ self._generate_schema(arg, f"{path}/prefixItems/{i}", None)
313
+ )
314
+ schema["prefixItems"] = prefix_items
315
+ return self._apply_transform(schema, type_, field, path)
316
+
317
+ # Handle Union types (choice)
318
+ if origin is Union or (UnionType and isinstance(type_, UnionType)):
319
+ non_none_args = [a for a in args if a is not type(None)]
320
+ if len(non_none_args) > 1:
321
+ schema["type"] = "choice"
322
+ options = {}
323
+ for i, arg in enumerate(non_none_args):
324
+ option_name = self._get_type_name(arg)
325
+ options[option_name] = self._generate_schema(
326
+ arg, f"{path}/options/{option_name}", None
327
+ )
328
+ schema["options"] = options
329
+ return self._apply_transform(schema, type_, field, path)
330
+
331
+ # Handle dataclasses (objects)
332
+ if dataclasses.is_dataclass(type_) and isinstance(type_, type):
333
+ self._visited_types.add(type_)
334
+
335
+ schema["type"] = "object"
336
+
337
+ # Add title
338
+ if self.options.include_titles:
339
+ schema["title"] = type_.__name__
340
+
341
+ # Add description from docstring
342
+ if self.options.include_descriptions and type_.__doc__:
343
+ doc = inspect.cleandoc(type_.__doc__)
344
+ if doc:
345
+ schema["description"] = doc
346
+
347
+ properties: Dict[str, Any] = {}
348
+ required: List[str] = []
349
+
350
+ # Get type hints for the class
351
+ try:
352
+ hints = get_type_hints(type_)
353
+ except Exception:
354
+ hints = {}
355
+
356
+ for f in dataclasses.fields(type_):
357
+ # Get the actual type from hints if available
358
+ field_type = hints.get(f.name, f.type)
359
+
360
+ # Check if field is optional
361
+ field_origin = get_origin(field_type)
362
+ field_args = get_args(field_type)
363
+ field_is_optional = (
364
+ field_origin is Union or
365
+ (UnionType and isinstance(field_type, UnionType))
366
+ ) and type(None) in field_args
367
+
368
+ # Generate field schema
369
+ prop_schema = self._generate_schema(
370
+ field_type,
371
+ f"{path}/properties/{f.name}",
372
+ f
373
+ )
374
+
375
+ # Apply field metadata constraints
376
+ self._apply_field_constraints(prop_schema, f)
377
+
378
+ # Add description from field metadata or default
379
+ if self.options.include_descriptions:
380
+ if FieldConstraints.DESCRIPTION in f.metadata:
381
+ prop_schema["description"] = f.metadata[FieldConstraints.DESCRIPTION]
382
+
383
+ # Add title from field metadata
384
+ if self.options.include_titles:
385
+ if FieldConstraints.TITLE in f.metadata:
386
+ prop_schema["title"] = f.metadata[FieldConstraints.TITLE]
387
+
388
+ # Add default value
389
+ if self.options.include_defaults:
390
+ if f.default is not dataclasses.MISSING:
391
+ prop_schema["default"] = self._serialize_default(f.default)
392
+ elif f.default_factory is not dataclasses.MISSING:
393
+ # We can include a hint that there's a default factory
394
+ pass # Skip factory defaults as they're dynamic
395
+
396
+ properties[f.name] = prop_schema
397
+
398
+ # Determine if required
399
+ has_default = (
400
+ f.default is not dataclasses.MISSING or
401
+ f.default_factory is not dataclasses.MISSING
402
+ )
403
+ if not field_is_optional and not has_default:
404
+ required.append(f.name)
405
+
406
+ schema["properties"] = properties
407
+ if required:
408
+ schema["required"] = required
409
+
410
+ self._visited_types.discard(type_)
411
+
412
+ return self._apply_transform(schema, type_, field, path)
413
+
414
+ def _apply_field_constraints(self, schema: dict, field: dataclasses.Field) -> None:
415
+ """Apply field metadata constraints to the schema."""
416
+ metadata = field.metadata
417
+
418
+ # String constraints
419
+ if FieldConstraints.MIN_LENGTH in metadata:
420
+ schema["minLength"] = metadata[FieldConstraints.MIN_LENGTH]
421
+ if FieldConstraints.MAX_LENGTH in metadata:
422
+ schema["maxLength"] = metadata[FieldConstraints.MAX_LENGTH]
423
+ if FieldConstraints.PATTERN in metadata:
424
+ schema["pattern"] = metadata[FieldConstraints.PATTERN]
425
+
426
+ # Numeric constraints
427
+ if FieldConstraints.MINIMUM in metadata:
428
+ schema["minimum"] = metadata[FieldConstraints.MINIMUM]
429
+ if FieldConstraints.MAXIMUM in metadata:
430
+ schema["maximum"] = metadata[FieldConstraints.MAXIMUM]
431
+ if FieldConstraints.EXCLUSIVE_MINIMUM in metadata:
432
+ schema["exclusiveMinimum"] = metadata[FieldConstraints.EXCLUSIVE_MINIMUM]
433
+ if FieldConstraints.EXCLUSIVE_MAXIMUM in metadata:
434
+ schema["exclusiveMaximum"] = metadata[FieldConstraints.EXCLUSIVE_MAXIMUM]
435
+ if FieldConstraints.MULTIPLE_OF in metadata:
436
+ schema["multipleOf"] = metadata[FieldConstraints.MULTIPLE_OF]
437
+
438
+ # Array constraints
439
+ if FieldConstraints.MIN_ITEMS in metadata:
440
+ schema["minItems"] = metadata[FieldConstraints.MIN_ITEMS]
441
+ if FieldConstraints.MAX_ITEMS in metadata:
442
+ schema["maxItems"] = metadata[FieldConstraints.MAX_ITEMS]
443
+ if FieldConstraints.UNIQUE_ITEMS in metadata:
444
+ schema["uniqueItems"] = metadata[FieldConstraints.UNIQUE_ITEMS]
445
+
446
+ # Metadata
447
+ if FieldConstraints.DEPRECATED in metadata:
448
+ schema["deprecated"] = metadata[FieldConstraints.DEPRECATED]
449
+ if FieldConstraints.EXAMPLES in metadata:
450
+ schema["examples"] = metadata[FieldConstraints.EXAMPLES]
451
+
452
+ def _get_json_structure_type(self, type_: Type) -> Optional[str]:
453
+ """Map a Python type to a JSON Structure type string."""
454
+ # Check direct mapping
455
+ if type_ in self.TYPE_MAP:
456
+ return self.TYPE_MAP[type_]
457
+
458
+ # Handle origin types for generics
459
+ origin = get_origin(type_)
460
+ if origin is not None:
461
+ if origin in (list, List):
462
+ return "array"
463
+ if origin in (set, Set, frozenset, FrozenSet):
464
+ return "set"
465
+ if origin in (dict, Dict, Mapping):
466
+ return "map"
467
+ if origin in (tuple, Tuple):
468
+ return "tuple"
469
+
470
+ # Check if it's a dataclass
471
+ if dataclasses.is_dataclass(type_) and isinstance(type_, type):
472
+ return "object"
473
+
474
+ # Check if it's an enum
475
+ if isinstance(type_, type) and issubclass(type_, enum.Enum):
476
+ return "string"
477
+
478
+ return None
479
+
480
+ def _get_type_name(self, type_: Type) -> str:
481
+ """Get a friendly name for a type."""
482
+ if hasattr(type_, "__name__"):
483
+ return type_.__name__
484
+ return str(type_)
485
+
486
+ def _is_complex_type(self, type_: Type) -> bool:
487
+ """Check if a type is complex (can cause recursion)."""
488
+ if dataclasses.is_dataclass(type_) and isinstance(type_, type):
489
+ return True
490
+ return False
491
+
492
+ def _serialize_default(self, value: Any) -> Any:
493
+ """Serialize a default value to JSON-compatible format."""
494
+ if value is None:
495
+ return None
496
+ if isinstance(value, (str, int, float, bool)):
497
+ return value
498
+ if isinstance(value, (list, tuple)):
499
+ return [self._serialize_default(v) for v in value]
500
+ if isinstance(value, dict):
501
+ return {k: self._serialize_default(v) for k, v in value.items()}
502
+ if isinstance(value, enum.Enum):
503
+ return value.value if isinstance(value.value, str) else value.name
504
+ if isinstance(value, (date, datetime)):
505
+ return value.isoformat()
506
+ if isinstance(value, UUID):
507
+ return str(value)
508
+ if isinstance(value, Decimal):
509
+ return str(value)
510
+ # For other types, convert to string
511
+ return str(value)
512
+
513
+ def _apply_transform(
514
+ self,
515
+ schema: dict,
516
+ type_: Type,
517
+ field: Optional[dataclasses.Field],
518
+ path: str
519
+ ) -> dict:
520
+ """Apply transformation callback if configured."""
521
+ if self.options.transform_schema:
522
+ context = SchemaExporterContext(
523
+ type_=type_,
524
+ field=field,
525
+ path=path
526
+ )
527
+ return self.options.transform_schema(context, schema)
528
+ return schema
529
+
530
+
531
+ def export_schema(
532
+ type_: Type,
533
+ options: Optional[SchemaExporterOptions] = None
534
+ ) -> dict:
535
+ """
536
+ Export a JSON Structure schema from a Python type.
537
+
538
+ This is a convenience function that creates an exporter and exports the schema.
539
+
540
+ Args:
541
+ type_: The type to generate a schema for. Should be a dataclass.
542
+ options: Optional exporter options.
543
+
544
+ Returns:
545
+ A dictionary representing the JSON Structure schema.
546
+
547
+ Example:
548
+ >>> from dataclasses import dataclass, field
549
+ >>> from json_structure import export_schema, field_constraints
550
+ >>>
551
+ >>> @dataclass
552
+ ... class Person:
553
+ ... name: str = field(metadata=field_constraints(min_length=1, max_length=100))
554
+ ... age: int = field(metadata=field_constraints(minimum=0, maximum=150))
555
+ ... tags: List[str] = field(default_factory=list)
556
+ >>>
557
+ >>> schema = export_schema(Person)
558
+ >>> print(schema)
559
+ """
560
+ exporter = JsonStructureSchemaExporter(options)
561
+ return exporter.export(type_)