pyderive3 0.0.7__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.
- pyderive/__init__.py +60 -0
- pyderive/abc.py +204 -0
- pyderive/compat.py +245 -0
- pyderive/compile.py +362 -0
- pyderive/dataclasses.py +429 -0
- pyderive/extensions/README.md +5 -0
- pyderive/extensions/__init__.py +10 -0
- pyderive/extensions/serde/README.md +142 -0
- pyderive/extensions/serde/__init__.py +361 -0
- pyderive/extensions/serde/impl.py +122 -0
- pyderive/extensions/serde/serde.py +564 -0
- pyderive/extensions/serde/xml.py +288 -0
- pyderive/extensions/validate/README.md +83 -0
- pyderive/extensions/validate/__init__.py +199 -0
- pyderive/extensions/validate/generic.py +203 -0
- pyderive/extensions/validate/helpers.py +129 -0
- pyderive/extensions/validate/types.py +208 -0
- pyderive/extensions/validate/validators.py +666 -0
- pyderive/parse.py +157 -0
- pyderive/tests/__init__.py +16 -0
- pyderive/tests/dataclasses.py +156 -0
- pyderive/tests/extensions/__init__.py +15 -0
- pyderive/tests/extensions/serde.py +164 -0
- pyderive/tests/extensions/validate.py +289 -0
- pyderive3-0.0.7.dist-info/METADATA +189 -0
- pyderive3-0.0.7.dist-info/RECORD +28 -0
- pyderive3-0.0.7.dist-info/WHEEL +4 -0
- pyderive3-0.0.7.dist-info/licenses/LICENSE +21 -0
pyderive/__init__.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Custom DataClass Compilation Helpers
|
|
3
|
+
"""
|
|
4
|
+
from typing import Dict, Any
|
|
5
|
+
|
|
6
|
+
from .abc import *
|
|
7
|
+
from .parse import *
|
|
8
|
+
from .compile import *
|
|
9
|
+
from .dataclasses import *
|
|
10
|
+
from . import compat
|
|
11
|
+
|
|
12
|
+
#** Variables **#
|
|
13
|
+
__all__ = [
|
|
14
|
+
'compat',
|
|
15
|
+
|
|
16
|
+
'MISSING',
|
|
17
|
+
'InitVar',
|
|
18
|
+
'FrozenInstanceError',
|
|
19
|
+
'Fields',
|
|
20
|
+
'DefaultFactory',
|
|
21
|
+
'FieldType',
|
|
22
|
+
'FieldDef',
|
|
23
|
+
'Field',
|
|
24
|
+
'FlatStruct',
|
|
25
|
+
'ClassStruct',
|
|
26
|
+
'DataClassLike',
|
|
27
|
+
|
|
28
|
+
'remove_field',
|
|
29
|
+
'parse_fields',
|
|
30
|
+
'flatten_fields',
|
|
31
|
+
|
|
32
|
+
'create_init',
|
|
33
|
+
'create_repr',
|
|
34
|
+
'create_compare',
|
|
35
|
+
'create_hash',
|
|
36
|
+
'assign_func',
|
|
37
|
+
'gen_slots',
|
|
38
|
+
'add_slots',
|
|
39
|
+
'freeze_fields',
|
|
40
|
+
|
|
41
|
+
'is_dataclass',
|
|
42
|
+
'field',
|
|
43
|
+
'fields',
|
|
44
|
+
'astuple',
|
|
45
|
+
'asdict',
|
|
46
|
+
'dataclass',
|
|
47
|
+
|
|
48
|
+
'BaseField',
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
#** Classes **#
|
|
52
|
+
|
|
53
|
+
@dataclass(recurse=True, init=True)
|
|
54
|
+
class BaseField(Field[TypeT]):
|
|
55
|
+
"""dataclass field instance w/ better defaults"""
|
|
56
|
+
name: str = ''
|
|
57
|
+
anno: TypeT = field(default=type)
|
|
58
|
+
default: Any = field(default_factory=lambda: MISSING)
|
|
59
|
+
default_factory: DefaultFactory = field(default_factory=lambda: MISSING)
|
|
60
|
+
metadata: Dict[str, Any] = field(default_factory=dict)
|
pyderive/abc.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Custom DataClass Internal Types
|
|
3
|
+
"""
|
|
4
|
+
from abc import abstractmethod
|
|
5
|
+
from enum import IntEnum
|
|
6
|
+
from typing import (
|
|
7
|
+
Any, Callable, Dict, Generic, List, Literal, Optional,
|
|
8
|
+
Protocol, Type, TypeVar, Union)
|
|
9
|
+
from typing_extensions import Annotated, Self, \
|
|
10
|
+
runtime_checkable, get_origin, get_args
|
|
11
|
+
|
|
12
|
+
#** Variables **#
|
|
13
|
+
__all__ = [
|
|
14
|
+
'has_default',
|
|
15
|
+
'get_initvar',
|
|
16
|
+
|
|
17
|
+
'T',
|
|
18
|
+
'F',
|
|
19
|
+
'TypeT',
|
|
20
|
+
'DataFunc',
|
|
21
|
+
|
|
22
|
+
'has_default',
|
|
23
|
+
|
|
24
|
+
'MISSING',
|
|
25
|
+
'InitVar',
|
|
26
|
+
'FrozenInstanceError',
|
|
27
|
+
'Fields',
|
|
28
|
+
'DefaultFactory',
|
|
29
|
+
'FieldType',
|
|
30
|
+
'FieldDef',
|
|
31
|
+
'Field',
|
|
32
|
+
'FlatStruct',
|
|
33
|
+
'ClassStruct',
|
|
34
|
+
'DataClassLike',
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
#: generic typevar
|
|
38
|
+
T = TypeVar('T')
|
|
39
|
+
|
|
40
|
+
#: generic typevar for field
|
|
41
|
+
F = TypeVar('F', bound='FieldDef')
|
|
42
|
+
|
|
43
|
+
#: generic typevar bound to type
|
|
44
|
+
TypeT = TypeVar('TypeT', bound=Type)
|
|
45
|
+
|
|
46
|
+
#: InitVar Implementation
|
|
47
|
+
InitVar = Annotated[T, 'INIT-VAR']
|
|
48
|
+
|
|
49
|
+
#: typehint for dataclass creator function
|
|
50
|
+
DataFunc = Callable[[TypeT], TypeT]
|
|
51
|
+
|
|
52
|
+
#: type definition for a list of fields
|
|
53
|
+
Fields = List['FieldDef']
|
|
54
|
+
|
|
55
|
+
#: optional dictionary typehint
|
|
56
|
+
OptDict = Optional[Dict[str, Any]]
|
|
57
|
+
|
|
58
|
+
#: callable factory type hint
|
|
59
|
+
DefaultFactory = Union['MISSING', None, Callable[[], Any]]
|
|
60
|
+
|
|
61
|
+
#: field validator function
|
|
62
|
+
FieldValidator = Callable[[Any, F, Any], Any]
|
|
63
|
+
|
|
64
|
+
#: optional field validator function
|
|
65
|
+
OptValidator = Optional[FieldValidator]
|
|
66
|
+
|
|
67
|
+
#: optional settings for when to hide values in repr
|
|
68
|
+
ReprHide = Union[Literal['null'], Literal['empty']]
|
|
69
|
+
|
|
70
|
+
#** Functions **#
|
|
71
|
+
|
|
72
|
+
def has_default(field: 'FieldDef') -> bool:
|
|
73
|
+
"""return true if field has default"""
|
|
74
|
+
return field.default is not MISSING or field.default_factory is not MISSING
|
|
75
|
+
|
|
76
|
+
def get_initvar(anno: Type) -> Optional[Type]:
|
|
77
|
+
"""return inner annotation if annotation is init-var"""
|
|
78
|
+
origin, args = get_origin(anno), get_args(anno)
|
|
79
|
+
if origin is Annotated and len(args) == 2 and args[1] == 'INIT-VAR':
|
|
80
|
+
return args[0]
|
|
81
|
+
|
|
82
|
+
#** Classes **#
|
|
83
|
+
|
|
84
|
+
class MISSING:
|
|
85
|
+
pass
|
|
86
|
+
|
|
87
|
+
class FrozenInstanceError(AttributeError):
|
|
88
|
+
pass
|
|
89
|
+
|
|
90
|
+
class FieldType(IntEnum):
|
|
91
|
+
STANDARD = 1
|
|
92
|
+
INIT_VAR = 2
|
|
93
|
+
|
|
94
|
+
@runtime_checkable
|
|
95
|
+
class FieldDef(Protocol[TypeT]):
|
|
96
|
+
name: str
|
|
97
|
+
anno: TypeT
|
|
98
|
+
default: Any = MISSING
|
|
99
|
+
default_factory: DefaultFactory = MISSING
|
|
100
|
+
init: bool = True
|
|
101
|
+
repr: bool = True
|
|
102
|
+
hash: Optional[bool] = None
|
|
103
|
+
compare: bool = True
|
|
104
|
+
iter: bool = True
|
|
105
|
+
kw_only: bool = False
|
|
106
|
+
frozen: bool = False
|
|
107
|
+
validator: OptValidator = None
|
|
108
|
+
metadata: Dict[str, Any] = {}
|
|
109
|
+
field_type: FieldType = FieldType.STANDARD
|
|
110
|
+
|
|
111
|
+
@abstractmethod
|
|
112
|
+
def __init__(self, name: str, anno: Type, default: Any = MISSING):
|
|
113
|
+
raise NotImplementedError
|
|
114
|
+
|
|
115
|
+
def __compile__(self, cls: Type):
|
|
116
|
+
"""run finalize when field variables are finished compiling"""
|
|
117
|
+
pass
|
|
118
|
+
|
|
119
|
+
class Field(FieldDef[TypeT]):
|
|
120
|
+
|
|
121
|
+
def __init__(self,
|
|
122
|
+
name: str,
|
|
123
|
+
anno: TypeT,
|
|
124
|
+
default: Any = MISSING,
|
|
125
|
+
default_factory: DefaultFactory = MISSING,
|
|
126
|
+
init: bool = True,
|
|
127
|
+
repr: bool = True,
|
|
128
|
+
hash: Optional[bool] = None,
|
|
129
|
+
compare: bool = True,
|
|
130
|
+
iter: bool = True,
|
|
131
|
+
kw_only: bool = False,
|
|
132
|
+
frozen: bool = False,
|
|
133
|
+
validator: OptValidator = None,
|
|
134
|
+
metadata: OptDict = None,
|
|
135
|
+
field_type: FieldType = FieldType.STANDARD
|
|
136
|
+
):
|
|
137
|
+
self.name = name
|
|
138
|
+
self.anno = anno
|
|
139
|
+
self.default = default
|
|
140
|
+
self.default_factory = default_factory
|
|
141
|
+
self.init = init
|
|
142
|
+
self.repr = repr
|
|
143
|
+
self.hash = hash
|
|
144
|
+
self.compare = compare
|
|
145
|
+
self.kw_only = kw_only
|
|
146
|
+
self.iter = iter
|
|
147
|
+
self.frozen = frozen
|
|
148
|
+
self.validator = validator
|
|
149
|
+
self.metadata = metadata or {}
|
|
150
|
+
self.field_type = field_type
|
|
151
|
+
|
|
152
|
+
class FlatStruct:
|
|
153
|
+
|
|
154
|
+
def __init__(self,
|
|
155
|
+
order: Optional[List[str]] = None,
|
|
156
|
+
fields: Optional[Dict[str, FieldDef]] = None,
|
|
157
|
+
):
|
|
158
|
+
self.order = order or []
|
|
159
|
+
self.fields = fields or dict()
|
|
160
|
+
|
|
161
|
+
def ordered_fields(self) -> Fields:
|
|
162
|
+
"""return fields in order they were assigned"""
|
|
163
|
+
return [self.fields[name] for name in self.order]
|
|
164
|
+
|
|
165
|
+
class ClassStruct(FlatStruct):
|
|
166
|
+
base: Optional[Type]
|
|
167
|
+
annotations: Optional[Dict[str, Any]]
|
|
168
|
+
|
|
169
|
+
def __init__(self, *args, parent: Optional[Self] = None, **kwargs):
|
|
170
|
+
super().__init__(*args, **kwargs)
|
|
171
|
+
self.parent = parent
|
|
172
|
+
self.base = None
|
|
173
|
+
self.annotations = None
|
|
174
|
+
|
|
175
|
+
def is_base_compiled(self, base: Type) -> bool:
|
|
176
|
+
"""
|
|
177
|
+
check if baseclass is already compiled
|
|
178
|
+
|
|
179
|
+
:param base: baseclass to confirm already compiled
|
|
180
|
+
:return: true if baseclass found in class-struct tree
|
|
181
|
+
"""
|
|
182
|
+
if self.base is not None and self.base == base:
|
|
183
|
+
return True
|
|
184
|
+
if self.parent is not None:
|
|
185
|
+
return self.parent.is_base_compiled(base)
|
|
186
|
+
return False
|
|
187
|
+
|
|
188
|
+
def is_anno_compiled(self, anno: Dict[str, Any]) -> bool:
|
|
189
|
+
"""
|
|
190
|
+
check if annotations are already compiled
|
|
191
|
+
|
|
192
|
+
:param anno: annotation to confirm already compiled
|
|
193
|
+
:return: true if annotations are already compiled
|
|
194
|
+
"""
|
|
195
|
+
if self.annotations is not None and self.annotations == anno:
|
|
196
|
+
return True
|
|
197
|
+
if self.parent is not None:
|
|
198
|
+
return self.parent.is_anno_compiled(anno)
|
|
199
|
+
return False
|
|
200
|
+
|
|
201
|
+
@runtime_checkable
|
|
202
|
+
class DataClassLike(Generic[F], Protocol):
|
|
203
|
+
"""Protocol for DataClass-Like Objects"""
|
|
204
|
+
__datafields__: List[F]
|
pyderive/compat.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Stdlib Dataclass Compatability Utils
|
|
3
|
+
"""
|
|
4
|
+
from functools import lru_cache
|
|
5
|
+
import sys
|
|
6
|
+
import importlib
|
|
7
|
+
from types import ModuleType
|
|
8
|
+
from typing import Dict, List, Optional, Set, Tuple, Type
|
|
9
|
+
from typing_extensions import get_origin, get_args
|
|
10
|
+
|
|
11
|
+
from .abc import MISSING, FieldDef, FieldType, Fields
|
|
12
|
+
|
|
13
|
+
#** Variables **#
|
|
14
|
+
__all__ = [
|
|
15
|
+
'monkey_patch',
|
|
16
|
+
'convert_fields',
|
|
17
|
+
'convert_params',
|
|
18
|
+
'std_convert_fields',
|
|
19
|
+
'std_assign_fields',
|
|
20
|
+
'std_convert_dataclass',
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
#: name of stdlib dataclass module
|
|
24
|
+
module_name = 'dataclasses'
|
|
25
|
+
|
|
26
|
+
#: preserved stdlib dataclass module for reference
|
|
27
|
+
stdlib_dataclasses: Optional[ModuleType] = None
|
|
28
|
+
|
|
29
|
+
#: compiled to stdlib cache
|
|
30
|
+
COMPILED_STDLIB = {}
|
|
31
|
+
|
|
32
|
+
#: origin annotation to valid annotation type
|
|
33
|
+
ANNO_MAP = {list: List, set: Set, tuple: Tuple, type: Type, dict: Dict}
|
|
34
|
+
|
|
35
|
+
#** Functions **#
|
|
36
|
+
|
|
37
|
+
def monkey_patch():
|
|
38
|
+
"""
|
|
39
|
+
monkey-patch replace dataclasses w/ pyderive version
|
|
40
|
+
"""
|
|
41
|
+
global stdlib_dataclasses
|
|
42
|
+
# skip repeated monkey-patching if already converted
|
|
43
|
+
stdlib = sys.modules.get(module_name)
|
|
44
|
+
if stdlib and stdlib is stdlib_dataclasses:
|
|
45
|
+
return
|
|
46
|
+
# generate custom module to export dataclass replacements
|
|
47
|
+
from . import dataclasses as derive
|
|
48
|
+
try:
|
|
49
|
+
stdlib_dataclasses = importlib.import_module(module_name)
|
|
50
|
+
except ImportError:
|
|
51
|
+
pass
|
|
52
|
+
sys.modules[module_name] = derive
|
|
53
|
+
|
|
54
|
+
def _import_std_dataclasses():
|
|
55
|
+
"""import stdlib dataclasses library"""
|
|
56
|
+
dataclasses = stdlib_dataclasses or sys.modules.get(module_name)
|
|
57
|
+
dataclasses = dataclasses or importlib.import_module(module_name)
|
|
58
|
+
return dataclasses
|
|
59
|
+
|
|
60
|
+
def is_stddataclass(cls) -> bool:
|
|
61
|
+
"""
|
|
62
|
+
check to see if class is a stdlib dataclass
|
|
63
|
+
|
|
64
|
+
:param cls: potential stdlib dataclass object
|
|
65
|
+
:return: true if cls is stdlib dataclass
|
|
66
|
+
"""
|
|
67
|
+
dataclasses = _import_std_dataclasses()
|
|
68
|
+
if not dataclasses:
|
|
69
|
+
return False
|
|
70
|
+
return dataclasses.is_dataclass(cls)
|
|
71
|
+
|
|
72
|
+
def convert_fields(cls, field: Type[FieldDef]) -> Fields:
|
|
73
|
+
"""
|
|
74
|
+
convert stdlib dataclasses to pyderive dataclass
|
|
75
|
+
|
|
76
|
+
:param cls: dataclass object-type to convert fields for
|
|
77
|
+
:param field: field definition to use when converting fields
|
|
78
|
+
:return: converted field attributes
|
|
79
|
+
"""
|
|
80
|
+
# ensure type is dataclass or return
|
|
81
|
+
dataclasses = _import_std_dataclasses()
|
|
82
|
+
if not dataclasses:
|
|
83
|
+
return []
|
|
84
|
+
if not dataclasses.is_dataclass(cls):
|
|
85
|
+
return []
|
|
86
|
+
# create ftype conversion
|
|
87
|
+
ftypes = {
|
|
88
|
+
dataclasses._FIELD: FieldType.STANDARD,
|
|
89
|
+
dataclasses._FIELD_INITVAR: FieldType.INIT_VAR,
|
|
90
|
+
}
|
|
91
|
+
# convert field-types
|
|
92
|
+
converted = []
|
|
93
|
+
for f in getattr(cls, dataclasses._FIELDS).values():
|
|
94
|
+
new = field(f.name, f.type, f.default)
|
|
95
|
+
for name in (k for k in f.__slots__ if not k.startswith('_')):
|
|
96
|
+
value = getattr(f, name)
|
|
97
|
+
if value is dataclasses.MISSING:
|
|
98
|
+
value = MISSING
|
|
99
|
+
setattr(new, name, value)
|
|
100
|
+
ftype = f._field_type
|
|
101
|
+
if ftype not in ftypes:
|
|
102
|
+
raise ValueError(f'{cls.__name__}.{f.name} invalid type: {ftype!r}')
|
|
103
|
+
new.field_type = ftypes[ftype]
|
|
104
|
+
converted.append(new)
|
|
105
|
+
return converted
|
|
106
|
+
|
|
107
|
+
def convert_params(cls):
|
|
108
|
+
"""
|
|
109
|
+
convert dataclass params to the correct-type if a dataclass
|
|
110
|
+
|
|
111
|
+
:param cls: stdlib dataclass to retireve parameters from
|
|
112
|
+
:return: pyderive dataclass parameters
|
|
113
|
+
"""
|
|
114
|
+
from .dataclasses import PARAMS_ATTR
|
|
115
|
+
# ensure type is dataclass or return
|
|
116
|
+
dataclasses = _import_std_dataclasses()
|
|
117
|
+
if not dataclasses:
|
|
118
|
+
return
|
|
119
|
+
if not dataclasses.is_dataclass(cls):
|
|
120
|
+
return
|
|
121
|
+
# just move params attribute
|
|
122
|
+
params = getattr(cls, dataclasses._PARAMS)
|
|
123
|
+
setattr(cls, PARAMS_ATTR, params)
|
|
124
|
+
|
|
125
|
+
def _convert_anno(anno: Type):
|
|
126
|
+
"""convert annotation for valid stdlib dataclass"""
|
|
127
|
+
# convert pyderive dataclass
|
|
128
|
+
from .dataclasses import is_dataclass
|
|
129
|
+
if is_dataclass(anno):
|
|
130
|
+
return std_convert_dataclass(anno)
|
|
131
|
+
# parse through complex type annotations
|
|
132
|
+
origin = get_origin(anno)
|
|
133
|
+
if origin is None:
|
|
134
|
+
return anno
|
|
135
|
+
origin = ANNO_MAP.get(origin) or origin
|
|
136
|
+
args = tuple([_convert_anno(subanno) for subanno in get_args(anno)])
|
|
137
|
+
return origin[args]
|
|
138
|
+
|
|
139
|
+
def std_convert_fields(cls):
|
|
140
|
+
"""
|
|
141
|
+
convert pyderive dataclass fields to stdlib dataclass fields
|
|
142
|
+
|
|
143
|
+
:param cls: pyderive dataclass
|
|
144
|
+
:return: stdlib dataclass fields list
|
|
145
|
+
"""
|
|
146
|
+
# confirm class is pyderive dataclass
|
|
147
|
+
from .dataclasses import MISSING, FIELD_ATTR, is_dataclass
|
|
148
|
+
dataclasses = _import_std_dataclasses()
|
|
149
|
+
if not is_dataclass(cls):
|
|
150
|
+
raise ValueError(f'{cls!r} is not a pyderive dataclass')
|
|
151
|
+
# generate translation layers
|
|
152
|
+
ftypes = {
|
|
153
|
+
FieldType.STANDARD: dataclasses._FIELD,
|
|
154
|
+
FieldType.INIT_VAR: dataclasses._FIELD_INITVAR,
|
|
155
|
+
}
|
|
156
|
+
ignore = {'anno', 'field_type'}
|
|
157
|
+
def _missing(v):
|
|
158
|
+
return dataclasses.MISSING if v is MISSING else v
|
|
159
|
+
# convert fields when required
|
|
160
|
+
stdfields = []
|
|
161
|
+
for field in getattr(cls, FIELD_ATTR):
|
|
162
|
+
# convert remaining attrs not contained in stdlib field into metadata
|
|
163
|
+
metadata = {}
|
|
164
|
+
for name, value in field.__dict__.items():
|
|
165
|
+
if name in ignore or name in dataclasses.Field.__slots__:
|
|
166
|
+
continue
|
|
167
|
+
metadata[name] = value
|
|
168
|
+
# generate stdfield and add to field definitions
|
|
169
|
+
stdfield = dataclasses.field(
|
|
170
|
+
init=field.init,
|
|
171
|
+
repr=field.repr,
|
|
172
|
+
hash=field.hash,
|
|
173
|
+
compare=field.compare,
|
|
174
|
+
metadata=metadata,
|
|
175
|
+
default=_missing(field.default),
|
|
176
|
+
default_factory=_missing(field.default_factory),
|
|
177
|
+
)
|
|
178
|
+
stdfield.name = field.name
|
|
179
|
+
stdfield.type = _convert_anno(field.anno)
|
|
180
|
+
stdfield._field_type = ftypes[field.field_type]
|
|
181
|
+
if sys.version_info.minor >= 10:
|
|
182
|
+
stdfield.kw_only = field.kw_only
|
|
183
|
+
# convert defaults to dataclasses if needed
|
|
184
|
+
if is_dataclass(stdfield.default_factory):
|
|
185
|
+
stdfield.default_factory = \
|
|
186
|
+
std_convert_dataclass(stdfield.default_factory)
|
|
187
|
+
stdfields.append(stdfield)
|
|
188
|
+
return stdfields
|
|
189
|
+
|
|
190
|
+
def std_assign_fields(cls):
|
|
191
|
+
"""
|
|
192
|
+
convert pyderive dataclass fields to std dataclass fields and assign
|
|
193
|
+
|
|
194
|
+
:param cls: pyderive dataclass
|
|
195
|
+
:return: stdlib compatable pyderive dataclass
|
|
196
|
+
"""
|
|
197
|
+
dataclasses = _import_std_dataclasses()
|
|
198
|
+
if not dataclasses:
|
|
199
|
+
return cls
|
|
200
|
+
fields = std_convert_fields(cls)
|
|
201
|
+
setattr(cls, dataclasses._FIELDS, {f.name:f for f in fields})
|
|
202
|
+
return cls
|
|
203
|
+
|
|
204
|
+
@lru_cache(maxsize=int(1e10))
|
|
205
|
+
def std_convert_dataclass(cls, **kwargs):
|
|
206
|
+
"""
|
|
207
|
+
convert pyderive dataclass to stdlib dataclass for 3rd party compatability
|
|
208
|
+
|
|
209
|
+
:param cls: pyderive dataclass
|
|
210
|
+
:return: stdlib dataclass
|
|
211
|
+
"""
|
|
212
|
+
# confirm class is pyderive dataclas
|
|
213
|
+
from .dataclasses import is_dataclass, PARAMS_ATTR
|
|
214
|
+
dataclasses = _import_std_dataclasses()
|
|
215
|
+
if dataclasses.is_dataclass(cls):
|
|
216
|
+
return cls
|
|
217
|
+
if not is_dataclass(cls):
|
|
218
|
+
raise ValueError(f'{cls!r} is not a pyderive dataclass')
|
|
219
|
+
# generate dataclass name/bases/fields
|
|
220
|
+
name = cls.__name__
|
|
221
|
+
bases = cls.__mro__
|
|
222
|
+
fields = std_convert_fields(cls)
|
|
223
|
+
attrs = [(f.name, f.type, f) for f in fields]
|
|
224
|
+
# generate dataclass kwargs based on python version
|
|
225
|
+
params = getattr(cls, PARAMS_ATTR)
|
|
226
|
+
kwargs.setdefault('init', bool(params.init))
|
|
227
|
+
kwargs.setdefault('repr', bool(params.repr))
|
|
228
|
+
kwargs.setdefault('eq', params.eq)
|
|
229
|
+
kwargs.setdefault('order', params.order)
|
|
230
|
+
kwargs.setdefault('unsafe_hash', params.unsafe_hash)
|
|
231
|
+
kwargs.setdefault('frozen', params.frozen)
|
|
232
|
+
if sys.version_info.minor >= 10:
|
|
233
|
+
kwargs.setdefault('match_args', params.match_args)
|
|
234
|
+
kwargs.setdefault('kw_only', params.kw_only)
|
|
235
|
+
kwargs.setdefault('slots', params.slots)
|
|
236
|
+
# finalize dataclass generation
|
|
237
|
+
dataclass = dataclasses.make_dataclass(name, attrs, bases=bases, **kwargs)
|
|
238
|
+
# #NOTE: this magic resolves some seemingly random issues when passing
|
|
239
|
+
# # dataclasses to other 3rd party libraries
|
|
240
|
+
@dataclasses.dataclass
|
|
241
|
+
class DataClass(dataclass):
|
|
242
|
+
pass
|
|
243
|
+
DataClass.__name__ = dataclass.__name__
|
|
244
|
+
DataClass.__qualname__ = dataclass.__qualname__
|
|
245
|
+
return DataClass
|