Generates a JSON schema that matches a decimal value. Args: schema: The core schema. Returns: The generated JSON schema.
(self, schema: core_schema.DecimalSchema)
| 686 | return json_schema |
| 687 | |
| 688 | def decimal_schema(self, schema: core_schema.DecimalSchema) -> JsonSchemaValue: |
| 689 | """Generates a JSON schema that matches a decimal value. |
| 690 | |
| 691 | Args: |
| 692 | schema: The core schema. |
| 693 | |
| 694 | Returns: |
| 695 | The generated JSON schema. |
| 696 | """ |
| 697 | |
| 698 | def get_decimal_pattern(schema: core_schema.DecimalSchema) -> str: |
| 699 | max_digits = schema.get('max_digits') |
| 700 | decimal_places = schema.get('decimal_places') |
| 701 | |
| 702 | pattern = ( |
| 703 | r'^(?!^[-+.]*$)[+-]?0*' # check it is not empty string and not one or sequence of ".+-" characters. |
| 704 | ) |
| 705 | |
| 706 | # Case 1: Both max_digits and decimal_places are set |
| 707 | if max_digits is not None and decimal_places is not None: |
| 708 | integer_places = max(0, max_digits - decimal_places) |
| 709 | pattern += ( |
| 710 | rf'(?:' |
| 711 | rf'\d{{0,{integer_places}}}' |
| 712 | rf'|' |
| 713 | rf'(?=[\d.]{{1,{max_digits + 1}}}0*$)' |
| 714 | rf'\d{{0,{integer_places}}}\.\d{{0,{decimal_places}}}0*$' |
| 715 | rf')' |
| 716 | ) |
| 717 | |
| 718 | # Case 2: Only max_digits is set |
| 719 | elif max_digits is not None and decimal_places is None: |
| 720 | pattern += ( |
| 721 | rf'(?:' |
| 722 | rf'\d{{0,{max_digits}}}' |
| 723 | rf'|' |
| 724 | rf'(?=[\d.]{{1,{max_digits + 1}}}0*$)' |
| 725 | rf'\d*\.\d*0*$' |
| 726 | rf')' |
| 727 | ) |
| 728 | |
| 729 | # Case 3: Only decimal_places is set |
| 730 | elif max_digits is None and decimal_places is not None: |
| 731 | pattern += rf'\d*\.?\d{{0,{decimal_places}}}0*$' |
| 732 | |
| 733 | # Case 4: Both are None (no restrictions) |
| 734 | else: |
| 735 | pattern += r'\d*\.?\d*$' # look for arbitrary integer or decimal |
| 736 | |
| 737 | return pattern |
| 738 | |
| 739 | json_schema = self.str_schema(core_schema.str_schema(pattern=get_decimal_pattern(schema))) |
| 740 | if self.mode == 'validation': |
| 741 | multiple_of = schema.get('multiple_of') |
| 742 | le = schema.get('le') |
| 743 | ge = schema.get('ge') |
| 744 | lt = schema.get('lt') |
| 745 | gt = schema.get('gt') |