pydantic-fixedwidth 0.1.0__py3-none-any.whl → 0.1.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.
Potentially problematic release.
This version of pydantic-fixedwidth might be problematic. Click here for more details.
- pydantic_fixedwidth/__init__.py +3 -0
- pydantic_fixedwidth/fixedwidth.py +170 -0
- pydantic_fixedwidth/py.typed +0 -0
- pydantic_fixedwidth-0.1.2.dist-info/METADATA +79 -0
- pydantic_fixedwidth-0.1.2.dist-info/RECORD +7 -0
- pydantic_fixedwidth-0.1.0.dist-info/METADATA +0 -26
- pydantic_fixedwidth-0.1.0.dist-info/RECORD +0 -4
- {pydantic_fixedwidth-0.1.0.dist-info → pydantic_fixedwidth-0.1.2.dist-info}/WHEEL +0 -0
- {pydantic_fixedwidth-0.1.0.dist-info → pydantic_fixedwidth-0.1.2.dist-info}/licenses/LICENSE +0 -0
|
@@ -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,79 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pydantic-fixedwidth
|
|
3
|
+
Version: 0.1.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
|
+
Provides-Extra: dev
|
|
13
|
+
Requires-Dist: mypy~=1.11; extra == 'dev'
|
|
14
|
+
Requires-Dist: ruff~=0.6; extra == 'dev'
|
|
15
|
+
Provides-Extra: test
|
|
16
|
+
Requires-Dist: coverage~=7.3; extra == 'test'
|
|
17
|
+
Requires-Dist: pytest-cov<7,>=5; extra == 'test'
|
|
18
|
+
Requires-Dist: pytest-sugar~=1.0; extra == 'test'
|
|
19
|
+
Requires-Dist: pytest~=8.0; extra == 'test'
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# pydantic-fixedwidth
|
|
23
|
+
|
|
24
|
+
[](https://opensource.org/licenses/MIT)
|
|
25
|
+
[](https://github.com/lasuillard/pydantic-fixedwidth/actions/workflows/ci.yaml)
|
|
26
|
+
[](https://codecov.io/gh/lasuillard/pydantic-fixedwidth)
|
|
27
|
+

|
|
28
|
+
|
|
29
|
+
Custom Pydantic models for serializing and deserializing fixed-width format data.
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
## 🚀 Quick Start
|
|
33
|
+
|
|
34
|
+
Install this package with pip:
|
|
35
|
+
|
|
36
|
+
```shell
|
|
37
|
+
$ pip install pydantic-fixedwidth
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Usage example:
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
from datetime import datetime, timezone
|
|
44
|
+
|
|
45
|
+
from pydantic_fixedwidth import Fixedwidth, Padding
|
|
46
|
+
from pydantic_fixedwidth import OrderedField as Field
|
|
47
|
+
|
|
48
|
+
tzinfo = timezone.utc
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class SomeRequest(Fixedwidth):
|
|
52
|
+
string: str = Field(length=8)
|
|
53
|
+
hangul: str = Field(length=6)
|
|
54
|
+
number: int = Field(length=10, justify="right", fill_char=b"0")
|
|
55
|
+
|
|
56
|
+
# Just an padding field
|
|
57
|
+
p_: str = Padding(length=10)
|
|
58
|
+
|
|
59
|
+
# This field will be ignored in ser/de
|
|
60
|
+
ignore: str = Field(length=10, default="IGNORE", exclude=True)
|
|
61
|
+
|
|
62
|
+
ts: datetime = Field(
|
|
63
|
+
length=20,
|
|
64
|
+
to_str=lambda dt: dt.strftime("%Y%m%d%H%M%S%f"),
|
|
65
|
+
from_str=lambda s: datetime.strptime(s, "%Y%m%d%H%M%S%f").replace(tzinfo=tzinfo),
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
some_request = SomeRequest(
|
|
70
|
+
string="<DFG&",
|
|
71
|
+
hangul="한글",
|
|
72
|
+
number=381,
|
|
73
|
+
ts=datetime(2024, 1, 23, 14, 11, 20, 124277, tzinfo=tzinfo),
|
|
74
|
+
)
|
|
75
|
+
b = some_request.format_bytes()
|
|
76
|
+
|
|
77
|
+
assert len(b) == 54
|
|
78
|
+
assert b == b"<DFG& \xed\x95\x9c\xea\xb8\x800000000381 20240123141120124277"
|
|
79
|
+
```
|
|
@@ -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.2.dist-info/METADATA,sha256=2RTSRyII7tl_OEeMBfX_I9OSHG2CYCVgE2H_8kHKolE,2587
|
|
5
|
+
pydantic_fixedwidth-0.1.2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
6
|
+
pydantic_fixedwidth-0.1.2.dist-info/licenses/LICENSE,sha256=Q5GkvYijQ2KTQ-QWhv43ilzCno4ZrzrEuATEQZd9rYo,1067
|
|
7
|
+
pydantic_fixedwidth-0.1.2.dist-info/RECORD,,
|
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: pydantic-fixedwidth
|
|
3
|
-
Version: 0.1.0
|
|
4
|
-
Summary: Custom Pydantic models for parsing and serializing fixed-width format of data.
|
|
5
|
-
License-Expression: MIT
|
|
6
|
-
License-File: LICENSE
|
|
7
|
-
Requires-Python: <4.0,>=3.9
|
|
8
|
-
Requires-Dist: pydantic<3,>=2
|
|
9
|
-
Provides-Extra: dev
|
|
10
|
-
Requires-Dist: mypy~=1.11; extra == 'dev'
|
|
11
|
-
Requires-Dist: ruff~=0.6; extra == 'dev'
|
|
12
|
-
Provides-Extra: test
|
|
13
|
-
Requires-Dist: coverage~=7.3; extra == 'test'
|
|
14
|
-
Requires-Dist: pytest-cov<7,>=5; extra == 'test'
|
|
15
|
-
Requires-Dist: pytest-sugar~=1.0; extra == 'test'
|
|
16
|
-
Requires-Dist: pytest~=8.0; extra == 'test'
|
|
17
|
-
Description-Content-Type: text/markdown
|
|
18
|
-
|
|
19
|
-
# pydantic-fixedwidth
|
|
20
|
-
|
|
21
|
-
[](https://opensource.org/licenses/MIT)
|
|
22
|
-
[](https://github.com/lasuillard/pydantic-fixedwidth/actions/workflows/ci.yaml)
|
|
23
|
-
[](https://codecov.io/gh/lasuillard/pydantic-fixedwidth)
|
|
24
|
-

|
|
25
|
-
|
|
26
|
-
Custom Pydantic models for parsing and serializing fixed-width format of data.
|
|
@@ -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,,
|
|
File without changes
|
{pydantic_fixedwidth-0.1.0.dist-info → pydantic_fixedwidth-0.1.2.dist-info}/licenses/LICENSE
RENAMED
|
File without changes
|