universal-mapper 1.0.0__tar.gz
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.
- universal_mapper-1.0.0/LICENSE +9 -0
- universal_mapper-1.0.0/PKG-INFO +151 -0
- universal_mapper-1.0.0/README.md +138 -0
- universal_mapper-1.0.0/pyproject.toml +82 -0
- universal_mapper-1.0.0/pyproject.toml.orig +85 -0
- universal_mapper-1.0.0/src/universal_mapper/__init__.py +3 -0
- universal_mapper-1.0.0/src/universal_mapper/accessors/__init__.py +13 -0
- universal_mapper-1.0.0/src/universal_mapper/accessors/abstract_base.py +42 -0
- universal_mapper-1.0.0/src/universal_mapper/accessors/accessor_factory.py +81 -0
- universal_mapper-1.0.0/src/universal_mapper/accessors/collection.py +69 -0
- universal_mapper-1.0.0/src/universal_mapper/accessors/dict.py +67 -0
- universal_mapper-1.0.0/src/universal_mapper/accessors/object_accessors/__init__.py +9 -0
- universal_mapper-1.0.0/src/universal_mapper/accessors/object_accessors/default.py +48 -0
- universal_mapper-1.0.0/src/universal_mapper/accessors/object_accessors/object_accessor.py +87 -0
- universal_mapper-1.0.0/src/universal_mapper/accessors/object_accessors/pydantic.py +40 -0
- universal_mapper-1.0.0/src/universal_mapper/accessors/object_accessors/sqlalchemy.py +75 -0
- universal_mapper-1.0.0/src/universal_mapper/exceptions.py +15 -0
- universal_mapper-1.0.0/src/universal_mapper/object_mapper.py +197 -0
- universal_mapper-1.0.0/src/universal_mapper/type_utils.py +93 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Mikhail Popov
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the " Software"), to deal in the Software without restriction, including without limitation on the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: universal-mapper
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: A Python library for mapping data between objects, models, and collections
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Dist: pydantic>=2 ; extra == 'pydantic'
|
|
8
|
+
Requires-Dist: sqlalchemy>=2 ; extra == 'sqlalchemy'
|
|
9
|
+
Requires-Python: >=3.12
|
|
10
|
+
Provides-Extra: pydantic
|
|
11
|
+
Provides-Extra: sqlalchemy
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# Universal Mapper
|
|
15
|
+
|
|
16
|
+
Universal Mapper is a Python library for mapping data between objects, models, and collections. It supports nested structures, updates to existing objects, and custom mapping rules.
|
|
17
|
+
|
|
18
|
+
The library requires Python 3.12 or later. It supports ordinary Python objects, dictionaries, and collections, with optional integrations for Pydantic and SQLAlchemy when those libraries are installed.
|
|
19
|
+
|
|
20
|
+
## License
|
|
21
|
+
|
|
22
|
+
Distributed under the [MIT License](LICENSE).
|
|
23
|
+
|
|
24
|
+
## Versions
|
|
25
|
+
|
|
26
|
+
### 1.0.0 — Unreleased
|
|
27
|
+
|
|
28
|
+
- Initial version with recursive mapping, object updates, and custom mapping rules.
|
|
29
|
+
- Optional support for Pydantic and SQLAlchemy models.
|
|
30
|
+
|
|
31
|
+
## Usage
|
|
32
|
+
|
|
33
|
+
### Map an object
|
|
34
|
+
|
|
35
|
+
For ordinary Python classes, fields are discovered from annotated `__init__` parameters.
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
from universal_mapper import ObjectMapper
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class User:
|
|
42
|
+
def __init__(self, id: int, name: str):
|
|
43
|
+
self.id = id
|
|
44
|
+
self.name = name
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class UserDto:
|
|
48
|
+
def __init__(self, id: int, name: str):
|
|
49
|
+
self.id = id
|
|
50
|
+
self.name = name
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
mapper = ObjectMapper()
|
|
54
|
+
user = User(id=1, name="Ada")
|
|
55
|
+
dto = mapper.map(user).to(UserDto)
|
|
56
|
+
|
|
57
|
+
assert (dto.id, dto.name) == (1, "Ada")
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### Update an existing object
|
|
61
|
+
|
|
62
|
+
The mapper can update an existing object. This example continues from the previous one.
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
updated = User(id=1, name="Grace")
|
|
66
|
+
mapper.map(updated).to(dto)
|
|
67
|
+
|
|
68
|
+
assert dto.name == "Grace"
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### Define a custom mapping rule
|
|
72
|
+
|
|
73
|
+
Use a mapping rule to calculate a target field from the source object.
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
from universal_mapper import ObjectMapper
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class Person:
|
|
80
|
+
def __init__(self, first_name: str, last_name: str):
|
|
81
|
+
self.first_name = first_name
|
|
82
|
+
self.last_name = last_name
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class PersonDto:
|
|
86
|
+
def __init__(self, full_name: str):
|
|
87
|
+
self.full_name = full_name
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
mapper = ObjectMapper()
|
|
91
|
+
mapper.add_mapping(
|
|
92
|
+
PersonDto,
|
|
93
|
+
{"full_name": lambda person: f"{person.first_name} {person.last_name}"},
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
dto = mapper.map(Person("Ada", "Lovelace")).to(PersonDto)
|
|
97
|
+
assert dto.full_name == "Ada Lovelace"
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
### Skip a field
|
|
101
|
+
|
|
102
|
+
Set a field's mapping rule to `None` to leave that field unchanged when updating an object. This example continues from the first usage example.
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
mapper = ObjectMapper()
|
|
106
|
+
mapper.add_mapping(UserDto, {"id": None})
|
|
107
|
+
|
|
108
|
+
existing = UserDto(id=1, name="Ada")
|
|
109
|
+
mapper.map(User(id=2, name="Grace")).to(existing)
|
|
110
|
+
|
|
111
|
+
assert (existing.id, existing.name) == (1, "Grace")
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### Map with a function
|
|
115
|
+
|
|
116
|
+
Register a function to define the complete mapping for a target type.
|
|
117
|
+
|
|
118
|
+
```python
|
|
119
|
+
from universal_mapper import ObjectMapper
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class Temperature:
|
|
123
|
+
def __init__(self, celsius: float):
|
|
124
|
+
self.celsius = celsius
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class TemperatureDto:
|
|
128
|
+
def __init__(self, fahrenheit: float):
|
|
129
|
+
self.fahrenheit = fahrenheit
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def to_fahrenheit(source: Temperature) -> TemperatureDto:
|
|
133
|
+
return TemperatureDto(fahrenheit=source.celsius * 9 / 5 + 32)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
mapper = ObjectMapper()
|
|
137
|
+
mapper.add_mapping(TemperatureDto, to_fahrenheit)
|
|
138
|
+
|
|
139
|
+
result = mapper.map(Temperature(20.0)).to(TemperatureDto)
|
|
140
|
+
assert result.fahrenheit == 68.0
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
See the [documentation](docs/README.md) for more examples and details about integrations, collections, and error handling.
|
|
144
|
+
|
|
145
|
+
## Inspiration
|
|
146
|
+
|
|
147
|
+
This project was inspired by [marazt/object-mapper](https://github.com/marazt/object-mapper).
|
|
148
|
+
|
|
149
|
+
## AI assistance
|
|
150
|
+
|
|
151
|
+
AI tools were used to assist with documentation, testing, and parts of the implementation. All changes are reviewed by the project maintainer.
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
# Universal Mapper
|
|
2
|
+
|
|
3
|
+
Universal Mapper is a Python library for mapping data between objects, models, and collections. It supports nested structures, updates to existing objects, and custom mapping rules.
|
|
4
|
+
|
|
5
|
+
The library requires Python 3.12 or later. It supports ordinary Python objects, dictionaries, and collections, with optional integrations for Pydantic and SQLAlchemy when those libraries are installed.
|
|
6
|
+
|
|
7
|
+
## License
|
|
8
|
+
|
|
9
|
+
Distributed under the [MIT License](LICENSE).
|
|
10
|
+
|
|
11
|
+
## Versions
|
|
12
|
+
|
|
13
|
+
### 1.0.0 — Unreleased
|
|
14
|
+
|
|
15
|
+
- Initial version with recursive mapping, object updates, and custom mapping rules.
|
|
16
|
+
- Optional support for Pydantic and SQLAlchemy models.
|
|
17
|
+
|
|
18
|
+
## Usage
|
|
19
|
+
|
|
20
|
+
### Map an object
|
|
21
|
+
|
|
22
|
+
For ordinary Python classes, fields are discovered from annotated `__init__` parameters.
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
from universal_mapper import ObjectMapper
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class User:
|
|
29
|
+
def __init__(self, id: int, name: str):
|
|
30
|
+
self.id = id
|
|
31
|
+
self.name = name
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class UserDto:
|
|
35
|
+
def __init__(self, id: int, name: str):
|
|
36
|
+
self.id = id
|
|
37
|
+
self.name = name
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
mapper = ObjectMapper()
|
|
41
|
+
user = User(id=1, name="Ada")
|
|
42
|
+
dto = mapper.map(user).to(UserDto)
|
|
43
|
+
|
|
44
|
+
assert (dto.id, dto.name) == (1, "Ada")
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### Update an existing object
|
|
48
|
+
|
|
49
|
+
The mapper can update an existing object. This example continues from the previous one.
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
updated = User(id=1, name="Grace")
|
|
53
|
+
mapper.map(updated).to(dto)
|
|
54
|
+
|
|
55
|
+
assert dto.name == "Grace"
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
### Define a custom mapping rule
|
|
59
|
+
|
|
60
|
+
Use a mapping rule to calculate a target field from the source object.
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
from universal_mapper import ObjectMapper
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class Person:
|
|
67
|
+
def __init__(self, first_name: str, last_name: str):
|
|
68
|
+
self.first_name = first_name
|
|
69
|
+
self.last_name = last_name
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class PersonDto:
|
|
73
|
+
def __init__(self, full_name: str):
|
|
74
|
+
self.full_name = full_name
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
mapper = ObjectMapper()
|
|
78
|
+
mapper.add_mapping(
|
|
79
|
+
PersonDto,
|
|
80
|
+
{"full_name": lambda person: f"{person.first_name} {person.last_name}"},
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
dto = mapper.map(Person("Ada", "Lovelace")).to(PersonDto)
|
|
84
|
+
assert dto.full_name == "Ada Lovelace"
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
### Skip a field
|
|
88
|
+
|
|
89
|
+
Set a field's mapping rule to `None` to leave that field unchanged when updating an object. This example continues from the first usage example.
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
mapper = ObjectMapper()
|
|
93
|
+
mapper.add_mapping(UserDto, {"id": None})
|
|
94
|
+
|
|
95
|
+
existing = UserDto(id=1, name="Ada")
|
|
96
|
+
mapper.map(User(id=2, name="Grace")).to(existing)
|
|
97
|
+
|
|
98
|
+
assert (existing.id, existing.name) == (1, "Grace")
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
### Map with a function
|
|
102
|
+
|
|
103
|
+
Register a function to define the complete mapping for a target type.
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
from universal_mapper import ObjectMapper
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class Temperature:
|
|
110
|
+
def __init__(self, celsius: float):
|
|
111
|
+
self.celsius = celsius
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class TemperatureDto:
|
|
115
|
+
def __init__(self, fahrenheit: float):
|
|
116
|
+
self.fahrenheit = fahrenheit
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def to_fahrenheit(source: Temperature) -> TemperatureDto:
|
|
120
|
+
return TemperatureDto(fahrenheit=source.celsius * 9 / 5 + 32)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
mapper = ObjectMapper()
|
|
124
|
+
mapper.add_mapping(TemperatureDto, to_fahrenheit)
|
|
125
|
+
|
|
126
|
+
result = mapper.map(Temperature(20.0)).to(TemperatureDto)
|
|
127
|
+
assert result.fahrenheit == 68.0
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
See the [documentation](docs/README.md) for more examples and details about integrations, collections, and error handling.
|
|
131
|
+
|
|
132
|
+
## Inspiration
|
|
133
|
+
|
|
134
|
+
This project was inspired by [marazt/object-mapper](https://github.com/marazt/object-mapper).
|
|
135
|
+
|
|
136
|
+
## AI assistance
|
|
137
|
+
|
|
138
|
+
AI tools were used to assist with documentation, testing, and parts of the implementation. All changes are reviewed by the project maintainer.
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "universal-mapper"
|
|
3
|
+
version = "1.0.0"
|
|
4
|
+
description = "A Python library for mapping data between objects, models, and collections"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.12"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
dependencies = []
|
|
10
|
+
|
|
11
|
+
[project.optional-dependencies]
|
|
12
|
+
pydantic = ["pydantic>=2"]
|
|
13
|
+
sqlalchemy = ["sqlalchemy>=2"]
|
|
14
|
+
|
|
15
|
+
[dependency-groups]
|
|
16
|
+
dev = [
|
|
17
|
+
"mypy>=2.4.1",
|
|
18
|
+
"pytest>=9.2.0",
|
|
19
|
+
"pytest-cov>=7.1.0",
|
|
20
|
+
"ruff>=0.17.6",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
[build-system]
|
|
24
|
+
requires = ["uv_build>=0.13.9,<0.14"]
|
|
25
|
+
build-backend = "uv_build"
|
|
26
|
+
|
|
27
|
+
[tool.mypy]
|
|
28
|
+
strict = true
|
|
29
|
+
exclude = [
|
|
30
|
+
"venv",
|
|
31
|
+
".venv",
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
[tool.pydantic-mypy]
|
|
35
|
+
init_forbid_extra = true
|
|
36
|
+
init_typed = true
|
|
37
|
+
warn_required_dynamic_aliases = true
|
|
38
|
+
warn_untyped_fields = true
|
|
39
|
+
|
|
40
|
+
[tool.ruff]
|
|
41
|
+
target-version = "py312"
|
|
42
|
+
exclude = []
|
|
43
|
+
line-length = 120
|
|
44
|
+
indent-width = 4
|
|
45
|
+
|
|
46
|
+
[tool.ruff.format]
|
|
47
|
+
quote-style = "double"
|
|
48
|
+
|
|
49
|
+
[tool.ruff.lint]
|
|
50
|
+
select = [
|
|
51
|
+
"E",
|
|
52
|
+
"W",
|
|
53
|
+
"F",
|
|
54
|
+
"I",
|
|
55
|
+
"B",
|
|
56
|
+
"C4",
|
|
57
|
+
"UP",
|
|
58
|
+
"ARG001",
|
|
59
|
+
]
|
|
60
|
+
ignore = [
|
|
61
|
+
"B008",
|
|
62
|
+
"W191",
|
|
63
|
+
"B904",
|
|
64
|
+
"UP045",
|
|
65
|
+
]
|
|
66
|
+
|
|
67
|
+
[tool.ruff.lint.pyupgrade]
|
|
68
|
+
keep-runtime-typing = true
|
|
69
|
+
|
|
70
|
+
[tool.pytest.ini_options]
|
|
71
|
+
pythonpath = "."
|
|
72
|
+
testpaths = ["tests"]
|
|
73
|
+
addopts = "-s --durations=10 -rf -q --junitxml=tests/results/junit.xml --cov --cov-report=term --cov-report=lcov:tests/results/lcov.info"
|
|
74
|
+
cache_dir = ".pytest_cache"
|
|
75
|
+
|
|
76
|
+
[tool.coverage.run]
|
|
77
|
+
branch = true
|
|
78
|
+
data_file = "tests/results/.coverage"
|
|
79
|
+
source = ["src"]
|
|
80
|
+
|
|
81
|
+
[tool.coverage.report]
|
|
82
|
+
show_missing = true
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "universal-mapper"
|
|
3
|
+
version = "1.0.0"
|
|
4
|
+
description = "A Python library for mapping data between objects, models, and collections"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.12"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
dependencies = []
|
|
10
|
+
|
|
11
|
+
[project.optional-dependencies]
|
|
12
|
+
pydantic = [
|
|
13
|
+
"pydantic>=2",
|
|
14
|
+
]
|
|
15
|
+
sqlalchemy = [
|
|
16
|
+
"sqlalchemy>=2",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
[dependency-groups]
|
|
20
|
+
dev = [
|
|
21
|
+
"mypy>=2.4.1",
|
|
22
|
+
"pytest>=9.2.0",
|
|
23
|
+
"pytest-cov>=7.1.0",
|
|
24
|
+
"ruff>=0.17.6",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
[build-system]
|
|
28
|
+
requires = ["uv_build>=0.13.9,<0.14"]
|
|
29
|
+
build-backend = "uv_build"
|
|
30
|
+
|
|
31
|
+
[tool.mypy]
|
|
32
|
+
strict = true
|
|
33
|
+
exclude = ["venv", ".venv"]
|
|
34
|
+
|
|
35
|
+
[tool.pydantic-mypy]
|
|
36
|
+
init_forbid_extra = true
|
|
37
|
+
init_typed = true
|
|
38
|
+
warn_required_dynamic_aliases = true
|
|
39
|
+
warn_untyped_fields = true
|
|
40
|
+
|
|
41
|
+
[tool.ruff]
|
|
42
|
+
target-version = "py312"
|
|
43
|
+
exclude = []
|
|
44
|
+
line-length = 120
|
|
45
|
+
indent-width = 4
|
|
46
|
+
|
|
47
|
+
[tool.ruff.format]
|
|
48
|
+
quote-style = "double"
|
|
49
|
+
|
|
50
|
+
[tool.ruff.lint]
|
|
51
|
+
select = [
|
|
52
|
+
"E", # pycodestyle errors
|
|
53
|
+
"W", # pycodestyle warnings
|
|
54
|
+
"F", # pyflakes
|
|
55
|
+
"I", # isort
|
|
56
|
+
"B", # flake8-bugbear
|
|
57
|
+
"C4", # flake8-comprehensions
|
|
58
|
+
"UP", # pyupgrade
|
|
59
|
+
"ARG001", # unused arguments in functions
|
|
60
|
+
]
|
|
61
|
+
|
|
62
|
+
ignore = [
|
|
63
|
+
"B008", # do not perform function calls in argument defaults
|
|
64
|
+
"W191", # indentation contains tabs
|
|
65
|
+
"B904", # Allow raising exceptions without from e, for HTTPException
|
|
66
|
+
"UP045", # Allow using Optional[] type annotation
|
|
67
|
+
]
|
|
68
|
+
|
|
69
|
+
[tool.ruff.lint.pyupgrade]
|
|
70
|
+
# Preserve types, even if a file imports `from __future__ import annotations`.
|
|
71
|
+
keep-runtime-typing = true
|
|
72
|
+
|
|
73
|
+
[tool.pytest.ini_options]
|
|
74
|
+
pythonpath = "."
|
|
75
|
+
testpaths = ["tests"]
|
|
76
|
+
addopts = "-s --durations=10 -rf -q --junitxml=tests/results/junit.xml --cov --cov-report=term --cov-report=lcov:tests/results/lcov.info"
|
|
77
|
+
cache_dir = ".pytest_cache"
|
|
78
|
+
|
|
79
|
+
[tool.coverage.run]
|
|
80
|
+
branch = true
|
|
81
|
+
data_file = "tests/results/.coverage"
|
|
82
|
+
source = ["src"]
|
|
83
|
+
|
|
84
|
+
[tool.coverage.report]
|
|
85
|
+
show_missing = true
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
from universal_mapper.accessors.abstract_base import (
|
|
2
|
+
InstanceMappingAccessor,
|
|
3
|
+
MappingAccessor,
|
|
4
|
+
TypeMappingAccessor,
|
|
5
|
+
)
|
|
6
|
+
from universal_mapper.accessors.accessor_factory import MappingAccessorFactory
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"InstanceMappingAccessor",
|
|
10
|
+
"MappingAccessor",
|
|
11
|
+
"MappingAccessorFactory",
|
|
12
|
+
"TypeMappingAccessor",
|
|
13
|
+
]
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from collections.abc import Iterator
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from universal_mapper.type_utils import TypeExtractor
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class MappingAccessor[T, K, V](ABC):
|
|
9
|
+
@classmethod
|
|
10
|
+
@abstractmethod
|
|
11
|
+
def can_map(cls, target: TypeExtractor[T]) -> bool: ...
|
|
12
|
+
|
|
13
|
+
@abstractmethod
|
|
14
|
+
def get_value_type(self, key: K) -> type[V]: ...
|
|
15
|
+
|
|
16
|
+
@abstractmethod
|
|
17
|
+
def __contains__(self, key: K) -> bool: ...
|
|
18
|
+
|
|
19
|
+
@abstractmethod
|
|
20
|
+
def __getitem__(self, key: K) -> Any | None: ...
|
|
21
|
+
|
|
22
|
+
@abstractmethod
|
|
23
|
+
def __setitem__(self, key: K, value: V) -> None: ...
|
|
24
|
+
|
|
25
|
+
@abstractmethod
|
|
26
|
+
def render(self) -> T: ...
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class TypeMappingAccessor[T, K, V](MappingAccessor[T, K, V]):
|
|
30
|
+
@abstractmethod
|
|
31
|
+
def __init__(self, accessor_type: type[T]): ...
|
|
32
|
+
|
|
33
|
+
def __getitem__(self, key: K) -> Any | None:
|
|
34
|
+
return None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class InstanceMappingAccessor[T, K, V](MappingAccessor[T, K, V]):
|
|
38
|
+
@abstractmethod
|
|
39
|
+
def __init__(self, accessor_type: type[T], instance: T): ...
|
|
40
|
+
|
|
41
|
+
@abstractmethod
|
|
42
|
+
def __iter__(self) -> Iterator[tuple[K, V]]: ...
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
from universal_mapper.accessors.abstract_base import (
|
|
4
|
+
InstanceMappingAccessor,
|
|
5
|
+
MappingAccessor,
|
|
6
|
+
TypeMappingAccessor,
|
|
7
|
+
)
|
|
8
|
+
from universal_mapper.accessors.collection import (
|
|
9
|
+
CollectionInstanceAccessor,
|
|
10
|
+
CollectionTypeAccessor,
|
|
11
|
+
)
|
|
12
|
+
from universal_mapper.accessors.dict import DictInstanceAccessor, DictTypeAccessor
|
|
13
|
+
from universal_mapper.accessors.object_accessors import (
|
|
14
|
+
DefaultObjectInstanceAccessor,
|
|
15
|
+
DefaultObjectTypeAccessor,
|
|
16
|
+
)
|
|
17
|
+
from universal_mapper.type_utils import TypeExtractor
|
|
18
|
+
|
|
19
|
+
_type_accessors: list[type[TypeMappingAccessor[Any, Any, Any]]] = []
|
|
20
|
+
_instance_accessors: list[type[InstanceMappingAccessor[Any, Any, Any]]] = []
|
|
21
|
+
|
|
22
|
+
try:
|
|
23
|
+
from universal_mapper.accessors.object_accessors.pydantic import (
|
|
24
|
+
PydanticObjectInstanceAccessor,
|
|
25
|
+
PydanticObjectTypeAccessor,
|
|
26
|
+
)
|
|
27
|
+
except ModuleNotFoundError as exc:
|
|
28
|
+
if exc.name != "pydantic":
|
|
29
|
+
raise
|
|
30
|
+
else:
|
|
31
|
+
_type_accessors.append(PydanticObjectTypeAccessor)
|
|
32
|
+
_instance_accessors.append(PydanticObjectInstanceAccessor)
|
|
33
|
+
|
|
34
|
+
try:
|
|
35
|
+
from universal_mapper.accessors.object_accessors.sqlalchemy import (
|
|
36
|
+
SqlAlchemyObjectInstanceAccessor,
|
|
37
|
+
SqlAlchemyObjectTypeAccessor,
|
|
38
|
+
)
|
|
39
|
+
except ModuleNotFoundError as exc:
|
|
40
|
+
if exc.name != "sqlalchemy":
|
|
41
|
+
raise
|
|
42
|
+
else:
|
|
43
|
+
_type_accessors.append(SqlAlchemyObjectTypeAccessor)
|
|
44
|
+
_instance_accessors.append(SqlAlchemyObjectInstanceAccessor)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class MappingAccessorFactory:
|
|
48
|
+
__type_iterators_registry: list[type[TypeMappingAccessor[Any, Any, Any]]] = [
|
|
49
|
+
CollectionTypeAccessor,
|
|
50
|
+
DictTypeAccessor,
|
|
51
|
+
*_type_accessors,
|
|
52
|
+
DefaultObjectTypeAccessor,
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
__instance_iterators_registry: list[type[InstanceMappingAccessor[Any, Any, Any]]] = [
|
|
56
|
+
CollectionInstanceAccessor,
|
|
57
|
+
DictInstanceAccessor,
|
|
58
|
+
*_instance_accessors,
|
|
59
|
+
DefaultObjectInstanceAccessor,
|
|
60
|
+
]
|
|
61
|
+
|
|
62
|
+
@classmethod
|
|
63
|
+
def get[T](cls, target: TypeExtractor[T]) -> MappingAccessor[T, Any, Any]:
|
|
64
|
+
if target.instance is None:
|
|
65
|
+
return cls.get_type_accessor(target)
|
|
66
|
+
else:
|
|
67
|
+
return cls.get_instance_accessor(target)
|
|
68
|
+
|
|
69
|
+
@classmethod
|
|
70
|
+
def get_type_accessor[T](cls, target: TypeExtractor[T]) -> TypeMappingAccessor[T, Any, Any]:
|
|
71
|
+
for iterator_type in cls.__type_iterators_registry:
|
|
72
|
+
if iterator_type.can_map(target):
|
|
73
|
+
return iterator_type(target.type)
|
|
74
|
+
raise NotImplementedError(f"Mapping iterator for type {target.type} not found")
|
|
75
|
+
|
|
76
|
+
@classmethod
|
|
77
|
+
def get_instance_accessor[T](cls, target: TypeExtractor[T]) -> InstanceMappingAccessor[T, Any, Any]:
|
|
78
|
+
for iterator_type in cls.__instance_iterators_registry:
|
|
79
|
+
if iterator_type.can_map(target):
|
|
80
|
+
return iterator_type(target.type, target.instance)
|
|
81
|
+
raise NotImplementedError(f"Mapping iterator for instance of type {target.type} not found")
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
from collections.abc import Collection, Iterator, Mapping
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
from universal_mapper.accessors.abstract_base import (
|
|
5
|
+
InstanceMappingAccessor,
|
|
6
|
+
TypeMappingAccessor,
|
|
7
|
+
)
|
|
8
|
+
from universal_mapper.type_utils import TypeExtractor, get_type_from_composite_type
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _can_map[T](target: TypeExtractor[T]) -> bool:
|
|
12
|
+
return (
|
|
13
|
+
issubclass(target.get_origin(), Collection)
|
|
14
|
+
and not issubclass(target.get_origin(), Mapping)
|
|
15
|
+
and not target.is_primitive()
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class CollectionTypeAccessor[T: Collection[Any]](TypeMappingAccessor[T, int, Any]):
|
|
20
|
+
def __init__(self, accessor_type: type[T]):
|
|
21
|
+
self.__accessor_type = accessor_type
|
|
22
|
+
self.__target_value_type: type = get_type_from_composite_type(accessor_type)
|
|
23
|
+
self.__container: list[Any] = []
|
|
24
|
+
|
|
25
|
+
@classmethod
|
|
26
|
+
def can_map(cls, target: TypeExtractor[T]) -> bool:
|
|
27
|
+
return _can_map(target)
|
|
28
|
+
|
|
29
|
+
def get_value_type(self, key: int) -> Any:
|
|
30
|
+
return self.__target_value_type
|
|
31
|
+
|
|
32
|
+
def __contains__(self, key: int) -> bool:
|
|
33
|
+
return key <= len(self.__container)
|
|
34
|
+
|
|
35
|
+
def __setitem__(self, key: int, value: Any) -> None:
|
|
36
|
+
self.__container.append(value)
|
|
37
|
+
|
|
38
|
+
def render(self) -> T:
|
|
39
|
+
return self.__accessor_type(self.__container) # type: ignore
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class CollectionInstanceAccessor[T: Collection[Any]](
|
|
43
|
+
InstanceMappingAccessor[T, int, Any]
|
|
44
|
+
):
|
|
45
|
+
def __init__(self, accessor_type: type[T], instance: T):
|
|
46
|
+
self.__accessor_type = accessor_type
|
|
47
|
+
self.__instance: T = instance
|
|
48
|
+
|
|
49
|
+
@classmethod
|
|
50
|
+
def can_map(cls, target: TypeExtractor[T]) -> bool:
|
|
51
|
+
return _can_map(target)
|
|
52
|
+
|
|
53
|
+
def get_value_type(self, key: int) -> Any:
|
|
54
|
+
return type(self.__instance[key]) # type: ignore [index]
|
|
55
|
+
|
|
56
|
+
def __contains__(self, item: int) -> bool:
|
|
57
|
+
return item < len(self.__instance)
|
|
58
|
+
|
|
59
|
+
def __getitem__(self, key: int) -> Any:
|
|
60
|
+
return self.__instance[key] # type: ignore [index]
|
|
61
|
+
|
|
62
|
+
def __setitem__(self, key: int, value: Any) -> None:
|
|
63
|
+
self.__instance[key] = value # type: ignore [index]
|
|
64
|
+
|
|
65
|
+
def __iter__(self) -> Iterator[tuple[int, Any]]:
|
|
66
|
+
return enumerate(self.__instance)
|
|
67
|
+
|
|
68
|
+
def render(self) -> T:
|
|
69
|
+
return self.__instance
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
from collections.abc import Iterator, Mapping
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
from universal_mapper.accessors.abstract_base import (
|
|
5
|
+
InstanceMappingAccessor,
|
|
6
|
+
TypeMappingAccessor,
|
|
7
|
+
)
|
|
8
|
+
from universal_mapper.type_utils import TypeExtractor, get_type_from_composite_type
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _can_map(target: TypeExtractor[Mapping[Any, Any]]) -> bool:
|
|
12
|
+
return issubclass(target.get_origin(), Mapping)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class DictTypeAccessor[T: Mapping[Any, Any]](
|
|
16
|
+
TypeMappingAccessor[Mapping[Any, Any], str, Any]
|
|
17
|
+
):
|
|
18
|
+
def __init__(self, accessor_type: type[T]):
|
|
19
|
+
self.__accessor_type = accessor_type
|
|
20
|
+
self.__target_value_type: type = get_type_from_composite_type(accessor_type)
|
|
21
|
+
self.__container: dict[Any, Any] = {}
|
|
22
|
+
|
|
23
|
+
@classmethod
|
|
24
|
+
def can_map(cls, target: TypeExtractor[Mapping[Any, Any]]) -> bool:
|
|
25
|
+
return _can_map(target)
|
|
26
|
+
|
|
27
|
+
def get_value_type(self, key: str) -> Any:
|
|
28
|
+
return self.__target_value_type
|
|
29
|
+
|
|
30
|
+
def __contains__(self, item: Any) -> bool:
|
|
31
|
+
return True
|
|
32
|
+
|
|
33
|
+
def __setitem__(self, key: Any, value: Any) -> None:
|
|
34
|
+
self.__container[key] = value
|
|
35
|
+
|
|
36
|
+
def render(self) -> T:
|
|
37
|
+
return self.__accessor_type(self.__container) # type: ignore
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class DictInstanceAccessor[T: Mapping[Any, Any]](
|
|
41
|
+
InstanceMappingAccessor[Mapping[Any, Any], str, Any]
|
|
42
|
+
):
|
|
43
|
+
def __init__(self, accessor_type: type[T], instance: T):
|
|
44
|
+
self.__accessor_type = accessor_type
|
|
45
|
+
self.__instance = instance
|
|
46
|
+
|
|
47
|
+
@classmethod
|
|
48
|
+
def can_map(cls, target: TypeExtractor[Mapping[Any, Any]]) -> bool:
|
|
49
|
+
return _can_map(target)
|
|
50
|
+
|
|
51
|
+
def get_value_type(self, key: str) -> Any:
|
|
52
|
+
return type(self.__instance[key])
|
|
53
|
+
|
|
54
|
+
def __contains__(self, item: Any) -> bool:
|
|
55
|
+
return item in self.__instance
|
|
56
|
+
|
|
57
|
+
def __getitem__(self, key: Any) -> Any:
|
|
58
|
+
return self.__instance[key]
|
|
59
|
+
|
|
60
|
+
def __setitem__(self, key: Any, value: Any) -> None:
|
|
61
|
+
self.__instance[key] = value # type: ignore
|
|
62
|
+
|
|
63
|
+
def __iter__(self) -> Iterator[tuple[str, Any]]:
|
|
64
|
+
return iter(self.__instance.items())
|
|
65
|
+
|
|
66
|
+
def render(self) -> T:
|
|
67
|
+
return self.__instance
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
from typing import Any, cast, get_type_hints
|
|
2
|
+
|
|
3
|
+
from universal_mapper.accessors.object_accessors.object_accessor import (
|
|
4
|
+
ObjectAccessorMixin,
|
|
5
|
+
ObjectInstanceAccessor,
|
|
6
|
+
ObjectTypeAccessor,
|
|
7
|
+
)
|
|
8
|
+
from universal_mapper.type_utils import TypeExtractor
|
|
9
|
+
|
|
10
|
+
_IGNORED_FIELDS = ("return", "args", "kwargs")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class DefaultObjectMixin[T: object](ObjectAccessorMixin[T]):
|
|
14
|
+
@classmethod
|
|
15
|
+
def _can_map(cls, target: TypeExtractor[T]) -> bool:
|
|
16
|
+
# supports only objects with defined constructors
|
|
17
|
+
try:
|
|
18
|
+
annotations = target.type.__init__.__annotations__
|
|
19
|
+
except AttributeError:
|
|
20
|
+
return False
|
|
21
|
+
return any(field not in _IGNORED_FIELDS for field in annotations)
|
|
22
|
+
|
|
23
|
+
def get_fields(self, target_cls: type[T]) -> list[str]:
|
|
24
|
+
result = []
|
|
25
|
+
for field in target_cls.__init__.__annotations__.keys():
|
|
26
|
+
if field not in _IGNORED_FIELDS:
|
|
27
|
+
result.append(field)
|
|
28
|
+
return result
|
|
29
|
+
|
|
30
|
+
def get_field_type(self, target_cls: type[T], field: str) -> Any:
|
|
31
|
+
type_hints = get_type_hints(target_cls.__init__)
|
|
32
|
+
return type_hints.get(field, Any)
|
|
33
|
+
|
|
34
|
+
def skip_instance_field(self, instance: T, field: str) -> bool:
|
|
35
|
+
return not hasattr(instance, field)
|
|
36
|
+
|
|
37
|
+
def create_instance(self, target_cls: type[T], data: dict[str, Any]) -> T:
|
|
38
|
+
return cast(target_cls, target_cls(**data)) # type: ignore
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class DefaultObjectTypeAccessor[T: object](
|
|
42
|
+
ObjectTypeAccessor[T], DefaultObjectMixin[T]
|
|
43
|
+
): ...
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class DefaultObjectInstanceAccessor[T: object](
|
|
47
|
+
ObjectInstanceAccessor[T], DefaultObjectMixin[T]
|
|
48
|
+
): ...
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
from abc import abstractmethod
|
|
2
|
+
from collections.abc import Iterator
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from universal_mapper.accessors.abstract_base import (
|
|
6
|
+
InstanceMappingAccessor,
|
|
7
|
+
TypeMappingAccessor,
|
|
8
|
+
)
|
|
9
|
+
from universal_mapper.type_utils import TypeExtractor
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ObjectAccessorMixin[T: object]:
|
|
13
|
+
@classmethod
|
|
14
|
+
@abstractmethod
|
|
15
|
+
def _can_map(cls, target: TypeExtractor[T]) -> bool: ...
|
|
16
|
+
|
|
17
|
+
@abstractmethod
|
|
18
|
+
def get_fields(self, target_cls: type[T]) -> list[str]: ...
|
|
19
|
+
|
|
20
|
+
@abstractmethod
|
|
21
|
+
def get_field_type(self, target_cls: type[T], field: str) -> Any: ...
|
|
22
|
+
|
|
23
|
+
@abstractmethod
|
|
24
|
+
def skip_instance_field(self, instance: T, field: str) -> bool: ...
|
|
25
|
+
|
|
26
|
+
@abstractmethod
|
|
27
|
+
def create_instance(self, target_cls: type[T], data_dict: dict[str, Any]) -> T: ...
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class ObjectTypeAccessor[T: object](
|
|
31
|
+
TypeMappingAccessor[T, str, Any], ObjectAccessorMixin[T]
|
|
32
|
+
):
|
|
33
|
+
def __init__(self, accessor_type: type[T]):
|
|
34
|
+
self.__accessor_type = accessor_type
|
|
35
|
+
self.__fields = self.get_fields(accessor_type)
|
|
36
|
+
self.__container: dict[Any, Any] = {}
|
|
37
|
+
|
|
38
|
+
@classmethod
|
|
39
|
+
def can_map(cls, target: TypeExtractor[T]) -> bool:
|
|
40
|
+
return cls._can_map(target)
|
|
41
|
+
|
|
42
|
+
def get_value_type(self, key: str) -> Any:
|
|
43
|
+
return self.get_field_type(self.__accessor_type, key)
|
|
44
|
+
|
|
45
|
+
def __contains__(self, item: Any) -> bool:
|
|
46
|
+
return item in self.__fields
|
|
47
|
+
|
|
48
|
+
def __setitem__(self, key: Any, value: Any) -> None:
|
|
49
|
+
self.__container[key] = value
|
|
50
|
+
|
|
51
|
+
def render(self) -> T:
|
|
52
|
+
return self.create_instance(self.__accessor_type, self.__container)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class ObjectInstanceAccessor[T: object](
|
|
56
|
+
InstanceMappingAccessor[T, str, Any], ObjectAccessorMixin[T]
|
|
57
|
+
):
|
|
58
|
+
def __init__(self, accessor_type: type[T], instance: T):
|
|
59
|
+
self.__accessor_type = accessor_type
|
|
60
|
+
self.__fields = self.get_fields(accessor_type)
|
|
61
|
+
self.__instance = instance
|
|
62
|
+
|
|
63
|
+
@classmethod
|
|
64
|
+
def can_map(cls, target: TypeExtractor[T]) -> bool:
|
|
65
|
+
return cls._can_map(target)
|
|
66
|
+
|
|
67
|
+
def get_value_type(self, key: str) -> Any:
|
|
68
|
+
return self.get_field_type(self.__accessor_type, key)
|
|
69
|
+
|
|
70
|
+
def __contains__(self, item: Any) -> bool:
|
|
71
|
+
return item in self.__fields and not self.skip_instance_field(
|
|
72
|
+
self.__instance, item
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
def __getitem__(self, key: Any) -> Any:
|
|
76
|
+
return getattr(self.__instance, key)
|
|
77
|
+
|
|
78
|
+
def __setitem__(self, key: Any, value: Any) -> None:
|
|
79
|
+
setattr(self.__instance, key, value)
|
|
80
|
+
|
|
81
|
+
def __iter__(self) -> Iterator[tuple[str, Any]]:
|
|
82
|
+
for field in self.__fields:
|
|
83
|
+
if not self.skip_instance_field(self.__instance, field):
|
|
84
|
+
yield (field, getattr(self.__instance, field))
|
|
85
|
+
|
|
86
|
+
def render(self) -> T:
|
|
87
|
+
return self.__instance
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
from pydantic import BaseModel
|
|
4
|
+
|
|
5
|
+
from universal_mapper.accessors.object_accessors.object_accessor import (
|
|
6
|
+
ObjectAccessorMixin,
|
|
7
|
+
ObjectInstanceAccessor,
|
|
8
|
+
ObjectTypeAccessor,
|
|
9
|
+
)
|
|
10
|
+
from universal_mapper.type_utils import TypeExtractor
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class PydanticObjectMixin[T: BaseModel](ObjectAccessorMixin[T]):
|
|
14
|
+
@classmethod
|
|
15
|
+
def _can_map(cls, target: TypeExtractor[T]) -> bool:
|
|
16
|
+
return issubclass(target.type, BaseModel)
|
|
17
|
+
|
|
18
|
+
def get_fields(self, target_cls: type[T]) -> list[str]:
|
|
19
|
+
return list(target_cls.model_fields.keys())
|
|
20
|
+
|
|
21
|
+
def get_field_type(self, target_cls: type[T], field: str) -> Any:
|
|
22
|
+
return target_cls.model_fields[field].annotation
|
|
23
|
+
|
|
24
|
+
def skip_instance_field(self, instance: T, field: str) -> bool:
|
|
25
|
+
if field not in instance.model_fields_set and getattr(instance, field) is None:
|
|
26
|
+
return True
|
|
27
|
+
return False
|
|
28
|
+
|
|
29
|
+
def create_instance(self, target_cls: type[T], data: dict[str, Any]) -> T:
|
|
30
|
+
return target_cls(**data)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class PydanticObjectTypeAccessor[T: BaseModel](
|
|
34
|
+
ObjectTypeAccessor[T], PydanticObjectMixin[T]
|
|
35
|
+
): ...
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class PydanticObjectInstanceAccessor[T: BaseModel](
|
|
39
|
+
ObjectInstanceAccessor[T], PydanticObjectMixin[T]
|
|
40
|
+
): ...
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
from typing import Any, get_args, get_origin
|
|
2
|
+
|
|
3
|
+
from sqlalchemy.inspection import inspect
|
|
4
|
+
from sqlalchemy.orm import ColumnProperty, DeclarativeBase, RelationshipProperty
|
|
5
|
+
|
|
6
|
+
from universal_mapper.accessors.object_accessors.object_accessor import (
|
|
7
|
+
ObjectAccessorMixin,
|
|
8
|
+
ObjectInstanceAccessor,
|
|
9
|
+
ObjectTypeAccessor,
|
|
10
|
+
)
|
|
11
|
+
from universal_mapper.type_utils import TypeExtractor
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class SqlAlchemyObjectMixin[T: DeclarativeBase](ObjectAccessorMixin[T]):
|
|
15
|
+
@classmethod
|
|
16
|
+
def _can_map(cls, target: TypeExtractor[T]) -> bool:
|
|
17
|
+
return inspect(target.type, raiseerr=False) is not None
|
|
18
|
+
|
|
19
|
+
def get_fields(self, target_cls: type[T]) -> list[str]:
|
|
20
|
+
inspector = inspect(target_cls)
|
|
21
|
+
return [x.key for x in inspector.attrs]
|
|
22
|
+
|
|
23
|
+
def get_field_type(self, target_cls: type[T], field: str) -> Any:
|
|
24
|
+
mapper = inspect(target_cls)
|
|
25
|
+
prop = mapper.attrs.get(field)
|
|
26
|
+
|
|
27
|
+
if isinstance(prop, RelationshipProperty):
|
|
28
|
+
related_type = prop.entity.class_
|
|
29
|
+
if prop.uselist:
|
|
30
|
+
return list[related_type] # type: ignore
|
|
31
|
+
return related_type
|
|
32
|
+
|
|
33
|
+
if isinstance(prop, ColumnProperty) and prop.columns:
|
|
34
|
+
try:
|
|
35
|
+
return prop.columns[0].type.python_type
|
|
36
|
+
except (NotImplementedError, AttributeError):
|
|
37
|
+
pass
|
|
38
|
+
|
|
39
|
+
# Fallback for edge cases where SQLAlchemy metadata does not expose python type.
|
|
40
|
+
annotation = target_cls.__annotations__.get(field, Any)
|
|
41
|
+
origin = get_origin(annotation)
|
|
42
|
+
args = get_args(annotation)
|
|
43
|
+
if origin is not None and args:
|
|
44
|
+
# Unwrap wrappers like Mapped[T] -> T.
|
|
45
|
+
return args[0]
|
|
46
|
+
return annotation
|
|
47
|
+
|
|
48
|
+
def skip_instance_field(self, instance: T, field: str) -> bool:
|
|
49
|
+
inspector = inspect(instance)
|
|
50
|
+
|
|
51
|
+
if field not in inspector.unloaded:
|
|
52
|
+
return False
|
|
53
|
+
|
|
54
|
+
# field is unloaded, skip if it's a relationship or a deferred column
|
|
55
|
+
prop = inspector.mapper.attrs.get(field)
|
|
56
|
+
if isinstance(prop, RelationshipProperty):
|
|
57
|
+
return True
|
|
58
|
+
|
|
59
|
+
if isinstance(prop, ColumnProperty) and prop.deferred:
|
|
60
|
+
return True
|
|
61
|
+
|
|
62
|
+
return False
|
|
63
|
+
|
|
64
|
+
def create_instance(self, target_cls: type[T], data: dict[str, Any]) -> T:
|
|
65
|
+
return target_cls(**data)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class SqlAlchemyObjectTypeAccessor[T: DeclarativeBase](
|
|
69
|
+
ObjectTypeAccessor[T], SqlAlchemyObjectMixin[T]
|
|
70
|
+
): ...
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class SqlAlchemyObjectInstanceAccessor[T: DeclarativeBase](
|
|
74
|
+
ObjectInstanceAccessor[T], SqlAlchemyObjectMixin[T]
|
|
75
|
+
): ...
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
class CircularReferenceError(RecursionError):
|
|
2
|
+
def __init__(self, *args: object) -> None:
|
|
3
|
+
super().__init__("Circular reference during recursive mapping was found")
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class UnknownTargetTypeError(TypeError):
|
|
7
|
+
def __init__(self, *args: object, field_type: type) -> None:
|
|
8
|
+
super().__init__(
|
|
9
|
+
f"Not able to deduce target type from source type: {field_type}"
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class TypeMismatchError(TypeError):
|
|
14
|
+
def __init__(self, *args: object, source_type: type, target_type: type) -> None:
|
|
15
|
+
super().__init__(f"Not able to convert type {source_type} to {target_type}")
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from decimal import Decimal, InvalidOperation
|
|
5
|
+
from typing import (
|
|
6
|
+
Annotated,
|
|
7
|
+
Any,
|
|
8
|
+
Literal,
|
|
9
|
+
TypeVar,
|
|
10
|
+
cast,
|
|
11
|
+
get_args,
|
|
12
|
+
get_origin,
|
|
13
|
+
overload,
|
|
14
|
+
)
|
|
15
|
+
from uuid import UUID
|
|
16
|
+
|
|
17
|
+
from universal_mapper.accessors import (
|
|
18
|
+
InstanceMappingAccessor,
|
|
19
|
+
MappingAccessor,
|
|
20
|
+
MappingAccessorFactory,
|
|
21
|
+
)
|
|
22
|
+
from universal_mapper.exceptions import CircularReferenceError, TypeMismatchError
|
|
23
|
+
from universal_mapper.type_utils import TypeExtractor, get_type_from_union_type
|
|
24
|
+
|
|
25
|
+
type MappingType = Callable[[Any], Any] | dict[str | int, Callable[[Any], Any] | None]
|
|
26
|
+
T = TypeVar("T")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class _MapperWrapper:
|
|
30
|
+
"""Handle the second part of the mapping process, `.to()`."""
|
|
31
|
+
|
|
32
|
+
def __init__(self, from_instance: Any, mapper: ObjectMapper) -> None:
|
|
33
|
+
self._from_instance = from_instance
|
|
34
|
+
self._mapper = mapper
|
|
35
|
+
|
|
36
|
+
@overload
|
|
37
|
+
def to(self, to_class_or_instance: type[T]) -> T:
|
|
38
|
+
"""Map an object to the specified class."""
|
|
39
|
+
|
|
40
|
+
@overload
|
|
41
|
+
def to(self, to_class_or_instance: T) -> T:
|
|
42
|
+
"""Update the fields of the specified object."""
|
|
43
|
+
|
|
44
|
+
def to(self, to_class_or_instance: type[T] | T) -> T:
|
|
45
|
+
"""Map to the specified class or update the fields of the specified object."""
|
|
46
|
+
_visited_ids_stack: set[int] = set()
|
|
47
|
+
return self._mapper._map_internal(
|
|
48
|
+
TypeExtractor(self._from_instance),
|
|
49
|
+
TypeExtractor(to_class_or_instance),
|
|
50
|
+
_visited_ids_stack,
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class ObjectMapper:
|
|
55
|
+
"""
|
|
56
|
+
Map objects to a specified class, including Pydantic and SQLAlchemy models.
|
|
57
|
+
|
|
58
|
+
Mapping can be automatic or configured with rules. Rules can be dictionaries
|
|
59
|
+
of lambda functions for individual fields or complete mapping functions.
|
|
60
|
+
Mapping can create a new object or update an existing object.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
__accessor_factory = MappingAccessorFactory()
|
|
64
|
+
|
|
65
|
+
def __init__(self) -> None:
|
|
66
|
+
self._mappings: dict[type[Any], MappingType] = {}
|
|
67
|
+
|
|
68
|
+
@classmethod
|
|
69
|
+
def __get_mapping_accessor(
|
|
70
|
+
cls, target: TypeExtractor[T]
|
|
71
|
+
) -> MappingAccessor[T, Any, Any]:
|
|
72
|
+
return cls.__accessor_factory.get(target)
|
|
73
|
+
|
|
74
|
+
def add_mapping(self, map_to: type[T], mapping: MappingType) -> None:
|
|
75
|
+
"""Add or overwrite a mapping rule."""
|
|
76
|
+
self._mappings[map_to] = mapping
|
|
77
|
+
|
|
78
|
+
def has_mapping(self, map_to: type[Any]) -> bool:
|
|
79
|
+
"""Check whether a mapping rule exists for the specified class."""
|
|
80
|
+
return map_to in self._mappings
|
|
81
|
+
|
|
82
|
+
@staticmethod
|
|
83
|
+
def _matches_literal(value: Any, literal_type: Any) -> bool:
|
|
84
|
+
return any(
|
|
85
|
+
type(value) is type(literal_value) and value == literal_value
|
|
86
|
+
for literal_value in get_args(literal_type)
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
@staticmethod
|
|
90
|
+
def _convert_primitive(
|
|
91
|
+
source: TypeExtractor[Any], target: TypeExtractor[Any]
|
|
92
|
+
) -> Any:
|
|
93
|
+
try:
|
|
94
|
+
if isinstance(source.instance, target.type):
|
|
95
|
+
return source.instance
|
|
96
|
+
except TypeError:
|
|
97
|
+
# target.type may be a typing construct that cannot be used with isinstance
|
|
98
|
+
pass
|
|
99
|
+
|
|
100
|
+
if target.type is UUID and source.type is str:
|
|
101
|
+
try:
|
|
102
|
+
return UUID(source.instance)
|
|
103
|
+
except (ValueError, TypeError):
|
|
104
|
+
raise TypeMismatchError(
|
|
105
|
+
source_type=source.type, target_type=target.type
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
if target.type is Decimal and source.type in {int, float, str}:
|
|
109
|
+
try:
|
|
110
|
+
return Decimal(str(source.instance))
|
|
111
|
+
except (InvalidOperation, ValueError):
|
|
112
|
+
raise TypeMismatchError(
|
|
113
|
+
source_type=source.type, target_type=target.type
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
if target.type is float:
|
|
117
|
+
try:
|
|
118
|
+
return float(source.instance) # type: ignore
|
|
119
|
+
except (ValueError, TypeError):
|
|
120
|
+
raise TypeMismatchError(
|
|
121
|
+
source_type=source.type, target_type=target.type
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
if source.type is Decimal and target.type is int:
|
|
125
|
+
decimal_value = cast(Decimal, source.instance)
|
|
126
|
+
if decimal_value == decimal_value.to_integral_value():
|
|
127
|
+
return int(decimal_value)
|
|
128
|
+
raise TypeMismatchError(source_type=source.type, target_type=target.type)
|
|
129
|
+
|
|
130
|
+
raise TypeMismatchError(source_type=source.type, target_type=target.type)
|
|
131
|
+
|
|
132
|
+
def map(self, from_instance: Any) -> _MapperWrapper:
|
|
133
|
+
"""Start mapping from an object."""
|
|
134
|
+
return _MapperWrapper(from_instance, self)
|
|
135
|
+
|
|
136
|
+
def _map_internal(
|
|
137
|
+
self,
|
|
138
|
+
source: TypeExtractor[Any],
|
|
139
|
+
target: TypeExtractor[T],
|
|
140
|
+
_visited_ids_stack: set[int],
|
|
141
|
+
) -> T:
|
|
142
|
+
"""Recursively map a source object to a type or an existing object."""
|
|
143
|
+
custom_mapping: MappingType = (
|
|
144
|
+
self._mappings[target.type] if target.type in self._mappings else {}
|
|
145
|
+
)
|
|
146
|
+
if callable(custom_mapping):
|
|
147
|
+
return custom_mapping(source.instance) # type: ignore
|
|
148
|
+
|
|
149
|
+
if source.instance is None:
|
|
150
|
+
return None # type: ignore
|
|
151
|
+
|
|
152
|
+
target.type = get_type_from_union_type(target.type)
|
|
153
|
+
|
|
154
|
+
if source.is_primitive():
|
|
155
|
+
origin = get_origin(target.type)
|
|
156
|
+
if origin is Annotated:
|
|
157
|
+
target.type = get_args(target.type)[0]
|
|
158
|
+
|
|
159
|
+
if get_origin(target.type) is Literal:
|
|
160
|
+
if not self._matches_literal(source.instance, target.type):
|
|
161
|
+
raise TypeMismatchError(
|
|
162
|
+
source_type=source.type, target_type=target.type
|
|
163
|
+
)
|
|
164
|
+
return source.instance # type: ignore
|
|
165
|
+
return self._convert_primitive(source, target) # type: ignore
|
|
166
|
+
|
|
167
|
+
if id(source.instance) in _visited_ids_stack:
|
|
168
|
+
raise CircularReferenceError
|
|
169
|
+
_visited_ids_stack.add(id(source.instance))
|
|
170
|
+
|
|
171
|
+
source_accessor = cast(
|
|
172
|
+
InstanceMappingAccessor[Any, Any, Any], self.__get_mapping_accessor(source)
|
|
173
|
+
)
|
|
174
|
+
target_accessor = self.__get_mapping_accessor(target)
|
|
175
|
+
|
|
176
|
+
for key, value in source_accessor:
|
|
177
|
+
if key not in target_accessor:
|
|
178
|
+
continue
|
|
179
|
+
if key in custom_mapping:
|
|
180
|
+
if custom_mapping[key] is None:
|
|
181
|
+
continue
|
|
182
|
+
target_accessor[key] = custom_mapping[key](source.instance) # type: ignore
|
|
183
|
+
continue
|
|
184
|
+
|
|
185
|
+
next_target = TypeExtractor(target_accessor.get_value_type(key))
|
|
186
|
+
next_target.instance = target_accessor[key]
|
|
187
|
+
target_accessor[key] = self._map_internal(
|
|
188
|
+
TypeExtractor(value), next_target, _visited_ids_stack
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
for key, mapping in custom_mapping.items():
|
|
192
|
+
if key not in source_accessor and mapping is not None:
|
|
193
|
+
target_accessor[key] = mapping(source.instance)
|
|
194
|
+
|
|
195
|
+
_visited_ids_stack.remove(id(source.instance))
|
|
196
|
+
|
|
197
|
+
return target_accessor.render()
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
from datetime import date, datetime
|
|
2
|
+
from decimal import Decimal
|
|
3
|
+
from types import UnionType
|
|
4
|
+
from typing import Any, Union, get_args, get_origin
|
|
5
|
+
from uuid import UUID
|
|
6
|
+
|
|
7
|
+
from universal_mapper.exceptions import UnknownTargetTypeError
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class TypeExtractor[T]:
|
|
11
|
+
__PRIMITIVE_BASE_TYPES = (
|
|
12
|
+
int,
|
|
13
|
+
float,
|
|
14
|
+
complex,
|
|
15
|
+
Decimal,
|
|
16
|
+
str,
|
|
17
|
+
bytes,
|
|
18
|
+
bytearray,
|
|
19
|
+
bool,
|
|
20
|
+
date,
|
|
21
|
+
datetime,
|
|
22
|
+
UUID,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
def __init__(self, type_or_instance: type[T] | T):
|
|
26
|
+
self.type: type[T]
|
|
27
|
+
self.instance: T | None = None
|
|
28
|
+
# If it's a class (like `UserDto`) or a generic alias (like `list[UserDto]`)
|
|
29
|
+
if (
|
|
30
|
+
isinstance(type_or_instance, type)
|
|
31
|
+
or get_origin(type_or_instance) is not None
|
|
32
|
+
):
|
|
33
|
+
self.type = type_or_instance # type: ignore [assignment]
|
|
34
|
+
# If it's an instance of a class (like `UserDto(...)`)
|
|
35
|
+
else:
|
|
36
|
+
self.type = type(type_or_instance)
|
|
37
|
+
self.instance = type_or_instance
|
|
38
|
+
|
|
39
|
+
def is_primitive(self) -> bool:
|
|
40
|
+
"""Check whether the object or type is primitive."""
|
|
41
|
+
if self.instance is not None:
|
|
42
|
+
return isinstance(self.instance, self.__PRIMITIVE_BASE_TYPES)
|
|
43
|
+
|
|
44
|
+
try:
|
|
45
|
+
return issubclass(self.type, self.__PRIMITIVE_BASE_TYPES)
|
|
46
|
+
except TypeError:
|
|
47
|
+
return False
|
|
48
|
+
|
|
49
|
+
def get_origin(self) -> type:
|
|
50
|
+
"""
|
|
51
|
+
Get the origin type from a composite type.
|
|
52
|
+
For example, return `list` for `list[UserDto]`.
|
|
53
|
+
"""
|
|
54
|
+
if get_origin(self.type) is not None:
|
|
55
|
+
return get_origin(self.type) # type: ignore
|
|
56
|
+
else:
|
|
57
|
+
return self.type
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def get_type_from_composite_type(target_type: Any) -> Any:
|
|
61
|
+
"""
|
|
62
|
+
Get the element type from a collection type.
|
|
63
|
+
For example, return `UserDto` for `list[UserDto]`.
|
|
64
|
+
"""
|
|
65
|
+
origin = get_origin(target_type)
|
|
66
|
+
args = get_args(target_type)
|
|
67
|
+
|
|
68
|
+
if origin is tuple and len(args) > 1 and args[1] is not ...:
|
|
69
|
+
raise NotImplementedError("Heterogenous tuples are not supported")
|
|
70
|
+
if len(args) == 1 or origin is tuple and args[1] is ...:
|
|
71
|
+
return args[0]
|
|
72
|
+
if origin is dict:
|
|
73
|
+
return args[1]
|
|
74
|
+
|
|
75
|
+
raise UnknownTargetTypeError(field_type=target_type)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def get_type_from_union_type(target_type: Any) -> Any:
|
|
79
|
+
"""
|
|
80
|
+
Recursively extract a type from a union.
|
|
81
|
+
Raise an error if a union contains more than one non-None type.
|
|
82
|
+
"""
|
|
83
|
+
origin = get_origin(target_type)
|
|
84
|
+
args = get_args(target_type)
|
|
85
|
+
|
|
86
|
+
if origin is Union or origin is UnionType:
|
|
87
|
+
non_none_args = [arg for arg in args if arg is not type(None)]
|
|
88
|
+
if len(non_none_args) == 1:
|
|
89
|
+
return get_type_from_union_type(non_none_args[0])
|
|
90
|
+
else:
|
|
91
|
+
raise UnknownTargetTypeError(field_type=target_type)
|
|
92
|
+
|
|
93
|
+
return target_type
|