pydantic-fixedwidth 0.2.2__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,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
@@ -0,0 +1,76 @@
1
+ Metadata-Version: 2.4
2
+ Name: pydantic-fixedwidth
3
+ Version: 0.2.2
4
+ Summary: Custom Pydantic models for parsing and serializing fixed-width format of data.
5
+ Project-URL: Homepage, https://github.com/lasuillard/pydantic-fixedwidth
6
+ Project-URL: Repository, https://github.com/lasuillard/pydantic-fixedwidth.git
7
+ Project-URL: Issues, https://github.com/lasuillard/pydantic-fixedwidth/issues
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Requires-Python: <4.0,>=3.9
11
+ Requires-Dist: pydantic<3,>=2
12
+ Description-Content-Type: text/markdown
13
+
14
+ # pydantic-fixedwidth
15
+
16
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
17
+ [![codecov](https://codecov.io/gh/lasuillard-s/pydantic-fixedwidth/graph/badge.svg?token=R5pQWB43DP)](https://codecov.io/gh/lasuillard-s/pydantic-fixedwidth)
18
+ [![PyPI - Version](https://img.shields.io/pypi/v/pydantic-fixedwidth)](https://pypi.org/project/pydantic-fixedwidth/)
19
+
20
+ Custom Pydantic models for serializing and deserializing fixed-width format data.
21
+
22
+
23
+ ## πŸš€ Quick Start
24
+
25
+ Install this package with pip:
26
+
27
+ ```shell
28
+ $ pip install pydantic-fixedwidth
29
+ ```
30
+
31
+ Usage example:
32
+
33
+ ```python
34
+ from datetime import datetime, timezone
35
+
36
+ from pydantic_fixedwidth import Fixedwidth, Padding
37
+ from pydantic_fixedwidth import OrderedField as Field
38
+
39
+ tzinfo = timezone.utc
40
+
41
+
42
+ class SomeRequest(Fixedwidth):
43
+ string: str = Field(length=8)
44
+ hangul: str = Field(length=6)
45
+ number: int = Field(length=10, justify="right", fill_char=b"0")
46
+
47
+ # Just an padding field
48
+ p_: str = Padding(length=10)
49
+
50
+ # This field will be ignored in ser/de
51
+ ignore: str = Field(length=10, default="IGNORE", exclude=True)
52
+
53
+ ts: datetime = Field(
54
+ length=20,
55
+ to_str=lambda dt: dt.strftime("%Y%m%d%H%M%S%f"),
56
+ from_str=lambda s: datetime.strptime(s, "%Y%m%d%H%M%S%f").replace(tzinfo=tzinfo),
57
+ )
58
+
59
+
60
+ # Format model to bytes
61
+ some_request = SomeRequest(
62
+ string="<DFG&",
63
+ hangul="ν•œκΈ€",
64
+ number=381,
65
+ ts=datetime(2024, 1, 23, 14, 11, 20, 124277, tzinfo=tzinfo),
66
+ )
67
+ b = some_request.format_bytes()
68
+
69
+ assert len(b) == 54
70
+ assert b == b"<DFG& \xed\x95\x9c\xea\xb8\x800000000381 20240123141120124277"
71
+
72
+ # Parse bytes into model
73
+ parsed_request = SomeRequest.parse_bytes(b)
74
+
75
+ assert parsed_request == some_request
76
+ ```
@@ -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.2.2.dist-info/METADATA,sha256=pyXQ1QcNV5MmbtxTsFq5ZXoS0639ZnNo6eMtpxtEGZ8,2288
5
+ pydantic_fixedwidth-0.2.2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
6
+ pydantic_fixedwidth-0.2.2.dist-info/licenses/LICENSE,sha256=Q5GkvYijQ2KTQ-QWhv43ilzCno4ZrzrEuATEQZd9rYo,1067
7
+ pydantic_fixedwidth-0.2.2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Yuchan Lee
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.