pydantic-fixedwidth 0.1.0__py3-none-any.whl → 0.1.1__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.

Potentially problematic release.


This version of pydantic-fixedwidth might be problematic. Click here for more details.

@@ -0,0 +1,3 @@
1
+ from .fixedwidth import Fixedwidth, Options, OrderedField, Padding
2
+
3
+ __all__ = ("Fixedwidth", "Options", "OrderedField", "Padding")
@@ -0,0 +1,170 @@
1
+ # noqa: D100
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+ from collections import OrderedDict
6
+ from functools import partial
7
+ from typing import Any, Callable, ClassVar, Literal
8
+
9
+ from pydantic import BaseModel, ConfigDict, Field
10
+ from pydantic.fields import FieldInfo # noqa: TC002
11
+ from typing_extensions import Self
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ __counter = 0
17
+
18
+
19
+ def OrderedField( # noqa: N802, PLR0913
20
+ *args: Any,
21
+ length: int,
22
+ justify: Literal["left", "right"] = "left",
23
+ fill_char: bytes = b" ",
24
+ encoding: str = "utf-8",
25
+ from_str: Callable[[str], Any] = lambda x: x.strip(),
26
+ to_str: Callable[[Any], str] = str,
27
+ **kwargs: Any,
28
+ ) -> Any:
29
+ """A wrapper for `pydantic.Field` with fixed-width related settings.
30
+
31
+ Args:
32
+ args: Positional arguments to be passed to `pydantic.Field`.
33
+ length: The fixed width length of the field.
34
+ justify: Justification of the field content.
35
+ fill_char: Byte used to fill the field.
36
+ encoding: Encoding used for the field.
37
+ from_str: Function to convert from string to the field type.
38
+ If field type is not `str`, user must provide it.
39
+ to_str: Function to convert from the field type to string.
40
+ kwargs: Additional keyword arguments to be passed to `pydantic.Field`.
41
+
42
+ Returns:
43
+ A `pydantic.Field` instance with fixed-width related settings.
44
+ """
45
+ global __counter # noqa: PLW0603
46
+
47
+ kwargs.setdefault("json_schema_extra", {})
48
+ field: FieldInfo = Field(*args, **kwargs)
49
+
50
+ options = Options(
51
+ field_info=field,
52
+ length=length,
53
+ order=__counter,
54
+ justify=justify,
55
+ fill_char=fill_char,
56
+ encoding=encoding,
57
+ from_str=from_str,
58
+ to_str=to_str,
59
+ )
60
+ options.save()
61
+ __counter += 1
62
+
63
+ return field
64
+
65
+
66
+ # Shortcuts for convenience
67
+ Padding = partial(OrderedField, default="")
68
+
69
+
70
+ class Fixedwidth(BaseModel):
71
+ """A base class for fixed-width models."""
72
+
73
+ _field_options: ClassVar[OrderedDict[str, Options]]
74
+
75
+ @classmethod
76
+ def __pydantic_init_subclass__(cls, *args: Any, **kwargs: Any) -> None:
77
+ super().__pydantic_init_subclass__(*args, **kwargs)
78
+
79
+ field_options = (
80
+ (
81
+ key,
82
+ Options.load(value),
83
+ )
84
+ for key, value in cls.model_fields.items()
85
+ if not value.exclude
86
+ )
87
+
88
+ sorted_by_order = sorted(field_options, key=lambda x: x[1].order)
89
+ cls._field_options = OrderedDict(sorted_by_order)
90
+
91
+ def format_bytes(self) -> bytes:
92
+ """Format the model as a fixed-width byte string."""
93
+ values: list[bytes] = []
94
+ for field_name, options in self._field_options.items():
95
+ value = getattr(self, field_name)
96
+ s = options.to_str(value)
97
+ b = str.encode(s, options.encoding)
98
+ if len(b) > options.length:
99
+ msg = f"Value of {field_name!r} ({b!r}; length: {len(b)}) is longer than field length {options.length}"
100
+ raise ValueError(msg)
101
+
102
+ b = (
103
+ b.ljust(options.length, options.fill_char)
104
+ if options.justify == "left"
105
+ else b.rjust(options.length, options.fill_char)
106
+ )
107
+ values.append(b)
108
+
109
+ result = b"".join(values)
110
+ logger.debug("Formatted %r into %r", self, result)
111
+
112
+ return result
113
+
114
+ @classmethod
115
+ def parse_bytes(cls, raw: bytes, **extras: Any) -> Self:
116
+ """Parse a fixed-width byte string into a model."""
117
+ values: dict[str, Any] = {}
118
+ index = 0
119
+ for field_name, options in cls._field_options.items():
120
+ b = raw[index : index + options.length]
121
+ s = bytes.decode(b, options.encoding)
122
+ value = options.from_str(s)
123
+ values[field_name] = value
124
+ index += options.length
125
+
126
+ obj = cls(**values, **extras)
127
+ logger.debug("Parsed %r into %r", raw, obj)
128
+
129
+ return obj
130
+
131
+
132
+ _OPTIONS_KEY = "__pydantic_fixedwidth__"
133
+ """Key to store `Options` in `field_info.json_schema_extra`."""
134
+
135
+
136
+ class Options(BaseModel):
137
+ """Options for a fixed-width field."""
138
+
139
+ model_config = ConfigDict(arbitrary_types_allowed=True)
140
+
141
+ field_info: FieldInfo
142
+
143
+ length: int
144
+ order: int
145
+ justify: Literal["left", "right"]
146
+ fill_char: bytes = Field(..., min_length=1, max_length=1)
147
+ encoding: str
148
+
149
+ from_str: Callable[[str], Any]
150
+ """Callable to create object from a string to the field type."""
151
+
152
+ to_str: Callable[[Any], str]
153
+ """Callable to cast the field type to a string."""
154
+
155
+ def save(self) -> None:
156
+ """Save `Options` to `field_info`."""
157
+ if not isinstance(self.field_info.json_schema_extra, dict):
158
+ msg = f"`json_schema_extra` must be a `dict`, but got: {type(self.field_info.json_schema_extra)!r}"
159
+ raise TypeError(msg)
160
+
161
+ self.field_info.json_schema_extra[_OPTIONS_KEY] = self.model_dump()
162
+
163
+ @classmethod
164
+ def load(cls, field_info: FieldInfo) -> Options:
165
+ """Load `Options` from `field_info`."""
166
+ if not isinstance(field_info.json_schema_extra, dict):
167
+ msg = f"`json_schema_extra` must be a `dict`, but got: {type(field_info.json_schema_extra)!r}"
168
+ raise TypeError(msg)
169
+
170
+ return cls.model_validate(field_info.json_schema_extra.get(_OPTIONS_KEY, {}))
File without changes
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pydantic-fixedwidth
3
- Version: 0.1.0
3
+ Version: 0.1.1
4
4
  Summary: Custom Pydantic models for parsing and serializing fixed-width format of data.
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -0,0 +1,7 @@
1
+ pydantic_fixedwidth/__init__.py,sha256=vVLHRSOlPVHzVbG3RGpUqNcBUPrnbbDSC03BwrMVMWA,131
2
+ pydantic_fixedwidth/fixedwidth.py,sha256=bYTPpWvGlwQM2l6LdOlADQvvCWNmXniLHnTutDjcKao,5379
3
+ pydantic_fixedwidth/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ pydantic_fixedwidth-0.1.1.dist-info/METADATA,sha256=RAIh5glXxFRdkNfBftYCRu_SgCNxHUM98_9yEl-gAjM,1236
5
+ pydantic_fixedwidth-0.1.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
6
+ pydantic_fixedwidth-0.1.1.dist-info/licenses/LICENSE,sha256=Q5GkvYijQ2KTQ-QWhv43ilzCno4ZrzrEuATEQZd9rYo,1067
7
+ pydantic_fixedwidth-0.1.1.dist-info/RECORD,,
@@ -1,4 +0,0 @@
1
- pydantic_fixedwidth-0.1.0.dist-info/METADATA,sha256=mRQ-onYkp-_tEAUng_GEfYq2wzzdVgbv_fcVrHagJTU,1236
2
- pydantic_fixedwidth-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
3
- pydantic_fixedwidth-0.1.0.dist-info/licenses/LICENSE,sha256=Q5GkvYijQ2KTQ-QWhv43ilzCno4ZrzrEuATEQZd9rYo,1067
4
- pydantic_fixedwidth-0.1.0.dist-info/RECORD,,