pyderive3 0.0.2__tar.gz → 0.0.3__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.
- {pyderive3-0.0.2 → pyderive3-0.0.3}/PKG-INFO +36 -1
- {pyderive3-0.0.2 → pyderive3-0.0.3}/README.md +35 -0
- {pyderive3-0.0.2 → pyderive3-0.0.3}/pyderive/__init__.py +5 -6
- pyderive3-0.0.3/pyderive/compat.py +92 -0
- {pyderive3-0.0.2 → pyderive3-0.0.3}/pyderive/compile.py +22 -20
- pyderive3-0.0.2/pyderive/dataclass.py → pyderive3-0.0.3/pyderive/dataclasses.py +85 -12
- {pyderive3-0.0.2 → pyderive3-0.0.3}/pyderive/parse.py +16 -7
- pyderive3-0.0.3/pyderive/tests/__init__.py +9 -0
- pyderive3-0.0.3/pyderive/tests/dataclasses.py +94 -0
- {pyderive3-0.0.2 → pyderive3-0.0.3}/pyderive3.egg-info/PKG-INFO +36 -1
- {pyderive3-0.0.2 → pyderive3-0.0.3}/pyderive3.egg-info/SOURCES.txt +4 -1
- {pyderive3-0.0.2 → pyderive3-0.0.3}/setup.py +1 -1
- {pyderive3-0.0.2 → pyderive3-0.0.3}/pyderive/abc.py +0 -0
- {pyderive3-0.0.2 → pyderive3-0.0.3}/pyderive3.egg-info/dependency_links.txt +0 -0
- {pyderive3-0.0.2 → pyderive3-0.0.3}/pyderive3.egg-info/requires.txt +0 -0
- {pyderive3-0.0.2 → pyderive3-0.0.3}/pyderive3.egg-info/top_level.txt +0 -0
- {pyderive3-0.0.2 → pyderive3-0.0.3}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: pyderive3
|
|
3
|
-
Version: 0.0.
|
|
3
|
+
Version: 0.0.3
|
|
4
4
|
Summary: Python3 Custom Data Class Helpers
|
|
5
5
|
Home-page: https://github.com/imgurbot12/pyderive
|
|
6
6
|
Author: Andrew Scott
|
|
@@ -88,6 +88,41 @@ for f in fields(foo):
|
|
|
88
88
|
print(f.name, f.custom_attr)
|
|
89
89
|
```
|
|
90
90
|
|
|
91
|
+
###### Backwards Compatibility
|
|
92
|
+
```python
|
|
93
|
+
import pyderive
|
|
94
|
+
import dataclasses
|
|
95
|
+
|
|
96
|
+
@dataclasses.dataclass
|
|
97
|
+
class Foo:
|
|
98
|
+
a: int
|
|
99
|
+
b: int = dataclasses.field(repr=False)
|
|
100
|
+
|
|
101
|
+
@pyderive.dataclass
|
|
102
|
+
class Bar(Foo):
|
|
103
|
+
c: int = pyderive.field(frozen=True)
|
|
104
|
+
|
|
105
|
+
f = Bar(1, 2, 3)
|
|
106
|
+
print(f)
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
###### Monkey Patching
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
from pyderive import compat
|
|
113
|
+
compat.monkey_patch()
|
|
114
|
+
|
|
115
|
+
from dataclasses import dataclass, field
|
|
116
|
+
|
|
117
|
+
@dataclass
|
|
118
|
+
class Foo:
|
|
119
|
+
a: int
|
|
120
|
+
b: int = field(frozen=True)
|
|
121
|
+
|
|
122
|
+
f = Foo(1, 2)
|
|
123
|
+
print(f)
|
|
124
|
+
```
|
|
125
|
+
|
|
91
126
|
##### Low Level Dataclass Compilation Tools
|
|
92
127
|
|
|
93
128
|
```python
|
|
@@ -74,6 +74,41 @@ for f in fields(foo):
|
|
|
74
74
|
print(f.name, f.custom_attr)
|
|
75
75
|
```
|
|
76
76
|
|
|
77
|
+
###### Backwards Compatibility
|
|
78
|
+
```python
|
|
79
|
+
import pyderive
|
|
80
|
+
import dataclasses
|
|
81
|
+
|
|
82
|
+
@dataclasses.dataclass
|
|
83
|
+
class Foo:
|
|
84
|
+
a: int
|
|
85
|
+
b: int = dataclasses.field(repr=False)
|
|
86
|
+
|
|
87
|
+
@pyderive.dataclass
|
|
88
|
+
class Bar(Foo):
|
|
89
|
+
c: int = pyderive.field(frozen=True)
|
|
90
|
+
|
|
91
|
+
f = Bar(1, 2, 3)
|
|
92
|
+
print(f)
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
###### Monkey Patching
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
from pyderive import compat
|
|
99
|
+
compat.monkey_patch()
|
|
100
|
+
|
|
101
|
+
from dataclasses import dataclass, field
|
|
102
|
+
|
|
103
|
+
@dataclass
|
|
104
|
+
class Foo:
|
|
105
|
+
a: int
|
|
106
|
+
b: int = field(frozen=True)
|
|
107
|
+
|
|
108
|
+
f = Foo(1, 2)
|
|
109
|
+
print(f)
|
|
110
|
+
```
|
|
111
|
+
|
|
77
112
|
##### Low Level Dataclass Compilation Tools
|
|
78
113
|
|
|
79
114
|
```python
|
|
@@ -6,10 +6,14 @@ from typing import Type, Any
|
|
|
6
6
|
from .abc import *
|
|
7
7
|
from .parse import *
|
|
8
8
|
from .compile import *
|
|
9
|
-
from .
|
|
9
|
+
from .dataclasses import *
|
|
10
|
+
from . import compat
|
|
10
11
|
|
|
11
12
|
#** Variables **#
|
|
12
13
|
__all__ = [
|
|
14
|
+
'compat',
|
|
15
|
+
|
|
16
|
+
'MISSING',
|
|
13
17
|
'InitVar',
|
|
14
18
|
'FrozenInstanceError',
|
|
15
19
|
'Fields',
|
|
@@ -40,11 +44,6 @@ __all__ = [
|
|
|
40
44
|
'DataClassLike',
|
|
41
45
|
|
|
42
46
|
'BaseField',
|
|
43
|
-
|
|
44
|
-
# compat exports
|
|
45
|
-
'InitVar',
|
|
46
|
-
'MISSING',
|
|
47
|
-
'FrozenInstanceError',
|
|
48
47
|
]
|
|
49
48
|
|
|
50
49
|
#** Classes **#
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Stdlib Dataclass Compatability Utils
|
|
3
|
+
"""
|
|
4
|
+
import sys
|
|
5
|
+
import importlib
|
|
6
|
+
from types import ModuleType
|
|
7
|
+
from typing import Optional, Type
|
|
8
|
+
|
|
9
|
+
from .abc import MISSING, FieldDef, FieldType, Fields
|
|
10
|
+
|
|
11
|
+
#** Variables **#
|
|
12
|
+
__all__ = ['monkey_patch', 'convert_fields', 'convert_params']
|
|
13
|
+
|
|
14
|
+
#: name of stdlib dataclass module
|
|
15
|
+
module_name = 'dataclasses'
|
|
16
|
+
|
|
17
|
+
#: preserved stdlib dataclass module for reference
|
|
18
|
+
stdlib_dataclasses: Optional[ModuleType] = None
|
|
19
|
+
|
|
20
|
+
#** Functions **#
|
|
21
|
+
|
|
22
|
+
def monkey_patch():
|
|
23
|
+
"""monkey-patch replace dataclasses w/ pyderive version"""
|
|
24
|
+
global stdlib_dataclasses
|
|
25
|
+
# skip repeated monkey-patching if already converted
|
|
26
|
+
stdlib = sys.modules.get(module_name)
|
|
27
|
+
if stdlib and stdlib is stdlib_dataclasses:
|
|
28
|
+
return
|
|
29
|
+
# generate custom module to export dataclass replacements
|
|
30
|
+
from . import dataclasses as derive
|
|
31
|
+
try:
|
|
32
|
+
stdlib_dataclasses = importlib.import_module(module_name)
|
|
33
|
+
except ImportError:
|
|
34
|
+
pass
|
|
35
|
+
sys.modules[module_name] = derive
|
|
36
|
+
|
|
37
|
+
def is_stddataclass(cls) -> bool:
|
|
38
|
+
"""
|
|
39
|
+
check to see if class is a stdlib dataclass
|
|
40
|
+
"""
|
|
41
|
+
dataclasses = stdlib_dataclasses or sys.modules.get(module_name)
|
|
42
|
+
if not dataclasses:
|
|
43
|
+
return False
|
|
44
|
+
return dataclasses.is_dataclass(cls)
|
|
45
|
+
|
|
46
|
+
def convert_fields(cls, field: Type[FieldDef]) -> Fields:
|
|
47
|
+
"""
|
|
48
|
+
convert stdlib dataclasses to pyderive dataclass
|
|
49
|
+
|
|
50
|
+
:param cls: dataclass object-type to convert fields for
|
|
51
|
+
:param field: field definition to use when converting fields
|
|
52
|
+
:return: converted field attributes
|
|
53
|
+
"""
|
|
54
|
+
# ensure type is dataclass or return
|
|
55
|
+
dataclasses = stdlib_dataclasses or sys.modules.get(module_name)
|
|
56
|
+
if not dataclasses:
|
|
57
|
+
return []
|
|
58
|
+
if not dataclasses.is_dataclass(cls):
|
|
59
|
+
return []
|
|
60
|
+
# create ftype conversion
|
|
61
|
+
ftypes = {
|
|
62
|
+
dataclasses._FIELD: FieldType.STANDARD,
|
|
63
|
+
dataclasses._FIELD_INITVAR: FieldType.INIT_VAR,
|
|
64
|
+
}
|
|
65
|
+
# convert field-types
|
|
66
|
+
converted = []
|
|
67
|
+
for f in getattr(cls, dataclasses._FIELDS).values():
|
|
68
|
+
new = field(f.name, f.type, f.default)
|
|
69
|
+
for name in (k for k in f.__slots__ if not k.startswith('_')):
|
|
70
|
+
value = getattr(f, name)
|
|
71
|
+
if value is dataclasses.MISSING:
|
|
72
|
+
value = MISSING
|
|
73
|
+
setattr(new, name, value)
|
|
74
|
+
ftype = f._field_type
|
|
75
|
+
if ftype not in ftypes:
|
|
76
|
+
raise ValueError(f'{cls.__name__}.{f.name} invalid type: {ftype!r}')
|
|
77
|
+
new.field_type = ftypes[ftype]
|
|
78
|
+
converted.append(new)
|
|
79
|
+
return converted
|
|
80
|
+
|
|
81
|
+
def convert_params(cls):
|
|
82
|
+
"""convert dataclass params to the correct-type if a dataclass"""
|
|
83
|
+
from .dataclasses import PARAMS_ATTR
|
|
84
|
+
# ensure type is dataclass or return
|
|
85
|
+
dataclasses = stdlib_dataclasses or sys.modules.get(module_name)
|
|
86
|
+
if not dataclasses:
|
|
87
|
+
return
|
|
88
|
+
if not dataclasses.is_dataclass(cls):
|
|
89
|
+
return
|
|
90
|
+
# just move params attribute
|
|
91
|
+
params = getattr(cls, dataclasses._PARAMS)
|
|
92
|
+
setattr(cls, PARAMS_ATTR, params)
|
|
@@ -3,7 +3,7 @@ DataClass Compiler Utilities
|
|
|
3
3
|
"""
|
|
4
4
|
from reprlib import recursive_repr
|
|
5
5
|
from types import FunctionType
|
|
6
|
-
from typing import Type, List, Optional, Any, Callable, Dict
|
|
6
|
+
from typing import Iterator, Type, List, Optional, Any, Callable, Dict
|
|
7
7
|
|
|
8
8
|
from .abc import *
|
|
9
9
|
|
|
@@ -116,22 +116,23 @@ def create_init(
|
|
|
116
116
|
# build parameter code
|
|
117
117
|
name = field.name
|
|
118
118
|
param = _init_param(field)
|
|
119
|
-
|
|
120
|
-
if field.default_factory is not MISSING:
|
|
121
|
-
raise TypeError(
|
|
122
|
-
f'init field {name!r} cannot have a default factory')
|
|
123
|
-
post.append(name)
|
|
119
|
+
value = _init_value(field, globals)
|
|
124
120
|
if field.init:
|
|
125
121
|
if kw_only or field.kw_only:
|
|
126
122
|
kwonly.append(param)
|
|
127
123
|
else:
|
|
128
124
|
args.append(param)
|
|
125
|
+
if field.field_type == FieldType.INIT_VAR:
|
|
126
|
+
if field.default_factory is not MISSING:
|
|
127
|
+
raise TypeError(
|
|
128
|
+
f'init field {name!r} cannot have a default factory')
|
|
129
|
+
post.append(name)
|
|
130
|
+
continue
|
|
129
131
|
# build body code
|
|
130
|
-
value = _init_value(field, globals)
|
|
131
132
|
assign = _init_assign(self_name, name, value, frozen or field.frozen)
|
|
132
133
|
body.append(assign)
|
|
133
134
|
# ensure body exists
|
|
134
|
-
if post_init
|
|
135
|
+
if post_init:
|
|
135
136
|
params = ', '.join(post)
|
|
136
137
|
body.append(f'self.{POST_INIT}({params})')
|
|
137
138
|
if not body:
|
|
@@ -142,6 +143,10 @@ def create_init(
|
|
|
142
143
|
args.extend(kwonly)
|
|
143
144
|
return _create_fn('__init__', args, body, locals, globals)
|
|
144
145
|
|
|
146
|
+
def _stdfields(fields: Fields) -> Iterator[FieldDef]:
|
|
147
|
+
"""retrieve only standard fields from fields-list"""
|
|
148
|
+
return (f for f in fields if f.field_type == FieldType.STANDARD)
|
|
149
|
+
|
|
145
150
|
def create_repr(fields: Fields) -> Callable:
|
|
146
151
|
"""
|
|
147
152
|
generate simple repr-function for the following field-structure
|
|
@@ -149,7 +154,7 @@ def create_repr(fields: Fields) -> Callable:
|
|
|
149
154
|
:param fields: ordered field used to generate repr-func
|
|
150
155
|
:param return: repr-function
|
|
151
156
|
"""
|
|
152
|
-
names = [f.name for f in fields if f.repr]
|
|
157
|
+
names = [f.name for f in _stdfields(fields) if f.repr]
|
|
153
158
|
body = 'return self.__class__.__qualname__ + f"(' + \
|
|
154
159
|
', '.join(f'{name}={{self.{name}!r}}' for name in names) + ')"'
|
|
155
160
|
func = _create_fn('__repr__', ['self'], [body])
|
|
@@ -171,7 +176,7 @@ def create_compare(fields: Fields, func: str, op: str) -> Callable:
|
|
|
171
176
|
:param op: function compare operation
|
|
172
177
|
:return: compare-function
|
|
173
178
|
"""
|
|
174
|
-
names = [f.name for f in fields if f.compare]
|
|
179
|
+
names = [f.name for f in _stdfields(fields) if f.compare]
|
|
175
180
|
self_t = _tuple_str(names, 'self')
|
|
176
181
|
other_t = _tuple_str(names, 'other')
|
|
177
182
|
return _create_fn(func, ['self', 'other'], [
|
|
@@ -187,7 +192,7 @@ def create_hash(fields: Fields) -> Callable:
|
|
|
187
192
|
:param fields: ordered fields used to generate hash-function
|
|
188
193
|
:return: hash-function
|
|
189
194
|
"""
|
|
190
|
-
names = [f.name for f in fields if f.hash]
|
|
195
|
+
names = [f.name for f in _stdfields(fields) if f.hash]
|
|
191
196
|
names_t = _tuple_str(names, 'self')
|
|
192
197
|
return _create_fn('__hash__', ['self'], [f'return hash({names_t})'])
|
|
193
198
|
|
|
@@ -215,9 +220,10 @@ def add_slots(cls: Type, fields: Fields, frozen: bool = False) -> Type:
|
|
|
215
220
|
generate slots for fields connected to the given class object
|
|
216
221
|
|
|
217
222
|
:param cls: class-object to assign slots onto
|
|
218
|
-
:param
|
|
223
|
+
:param fields: field structure to control slot definition
|
|
219
224
|
:return: updated class object
|
|
220
225
|
"""
|
|
226
|
+
fields = list(_stdfields(fields))
|
|
221
227
|
cls_dict = dict(cls.__dict__)
|
|
222
228
|
if '__slots__' in cls_dict:
|
|
223
229
|
raise TypeError(f'{cls.__name__} already specifies __slots__')
|
|
@@ -249,20 +255,16 @@ def add_slots(cls: Type, fields: Fields, frozen: bool = False) -> Type:
|
|
|
249
255
|
assign_func(cls, setstate)
|
|
250
256
|
return cls
|
|
251
257
|
|
|
252
|
-
def freeze_fields(cls: Type,
|
|
258
|
+
def freeze_fields(cls: Type, fields: Fields, frozen: bool = False):
|
|
253
259
|
"""
|
|
254
260
|
add custom __setattr__/__delattr__ funcs to prevent field modification
|
|
255
261
|
|
|
256
262
|
:param cls: class object to assign functions to
|
|
257
|
-
:param
|
|
263
|
+
:param fields: field structure to control frozen status
|
|
258
264
|
:param frozen: override field frozen status
|
|
259
265
|
"""
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
field = struct.fields[name]
|
|
263
|
-
if frozen or field.frozen:
|
|
264
|
-
fields.append(repr(name))
|
|
265
|
-
names = _tuple_str(fields)
|
|
266
|
+
fnames = [repr(f.name) for f in _stdfields(fields) if frozen or f.frozen]
|
|
267
|
+
names = _tuple_str(fnames)
|
|
266
268
|
globals = {'cls': cls, 'FrozenInstanceError': FrozenInstanceError}
|
|
267
269
|
ifstmt = f'if name in {names}:'
|
|
268
270
|
setattr = _create_fn('__setattr__', ['self', 'name', 'value'], [
|
|
@@ -9,12 +9,14 @@ from typing_extensions import dataclass_transform, runtime_checkable
|
|
|
9
9
|
from .abc import *
|
|
10
10
|
from .parse import *
|
|
11
11
|
from .compile import *
|
|
12
|
+
from .compat import is_stddataclass, convert_params
|
|
12
13
|
|
|
13
14
|
#** Variables **#
|
|
14
15
|
__all__ = [
|
|
15
16
|
'InitVar',
|
|
16
17
|
'MISSING',
|
|
17
18
|
'DataClassLike',
|
|
19
|
+
'FrozenInstanceError',
|
|
18
20
|
|
|
19
21
|
'is_dataclass',
|
|
20
22
|
'field',
|
|
@@ -26,6 +28,9 @@ __all__ = [
|
|
|
26
28
|
#: dataclass fields attribute
|
|
27
29
|
FIELD_ATTR = '__datafields__'
|
|
28
30
|
|
|
31
|
+
#: dataclas params attribute
|
|
32
|
+
PARAMS_ATTR = '__dataparams__'
|
|
33
|
+
|
|
29
34
|
#: field generic type
|
|
30
35
|
F = TypeVar('F', bound=FieldDef)
|
|
31
36
|
|
|
@@ -62,11 +67,6 @@ HASH_ACTIONS: Dict[Tuple[bool, bool, bool, bool], Any] = {
|
|
|
62
67
|
(True, True, True, True ): _hash_err,
|
|
63
68
|
}
|
|
64
69
|
|
|
65
|
-
@runtime_checkable
|
|
66
|
-
class DataClassLike(Generic[F], Protocol):
|
|
67
|
-
"""Protocol for DataClass-Like Objects"""
|
|
68
|
-
__datafields__: List[F]
|
|
69
|
-
|
|
70
70
|
#** Functions **#
|
|
71
71
|
|
|
72
72
|
def field(*_, **kwargs) -> Any:
|
|
@@ -85,23 +85,27 @@ def is_dataclass(cls) -> bool:
|
|
|
85
85
|
return hasattr(cls, FIELD_ATTR)
|
|
86
86
|
|
|
87
87
|
@overload
|
|
88
|
-
def fields(cls: Any) -> List[FieldDef]:
|
|
88
|
+
def fields(cls: Any, all_types: bool = False) -> List[FieldDef]:
|
|
89
89
|
...
|
|
90
90
|
|
|
91
91
|
@overload
|
|
92
|
-
def fields(cls: DataClassLike[F]) -> List[F]:
|
|
92
|
+
def fields(cls: 'DataClassLike[F]', all_types: bool = False) -> List[F]:
|
|
93
93
|
...
|
|
94
94
|
|
|
95
|
-
def fields(cls
|
|
95
|
+
def fields(cls, all_types: bool = False):
|
|
96
96
|
"""
|
|
97
97
|
retrieve fields associated w/ the given dataclass
|
|
98
98
|
|
|
99
|
-
:param cls:
|
|
100
|
-
:return
|
|
99
|
+
:param cls: dataclass object class instance
|
|
100
|
+
:param all_types: return all field-types or just standard fields
|
|
101
|
+
:return: field dictionary
|
|
101
102
|
"""
|
|
102
103
|
if not is_dataclass(cls):
|
|
103
104
|
raise TypeError('fields() should with a dataclass type or instance')
|
|
104
|
-
|
|
105
|
+
fields = getattr(cls, FIELD_ATTR)
|
|
106
|
+
if not all_types:
|
|
107
|
+
fields = [f for f in fields if f.field_type == FieldType.STANDARD]
|
|
108
|
+
return fields
|
|
105
109
|
|
|
106
110
|
def _asdict_inner(obj, rec: int, factory: Type[dict], lvl: int):
|
|
107
111
|
"""inner dictionary-ify function to convert dataclass fields into dict"""
|
|
@@ -159,12 +163,34 @@ def _process_class(
|
|
|
159
163
|
# valdiate settings
|
|
160
164
|
if order and not eq:
|
|
161
165
|
raise ValueError('eq must be true if order is true')
|
|
166
|
+
# convert params for stdlib dataclasses
|
|
167
|
+
isdataclass = is_dataclass(cls)
|
|
168
|
+
if not isdataclass and is_stddataclass(cls):
|
|
169
|
+
convert_params(cls)
|
|
162
170
|
# parse and conregate fields
|
|
163
171
|
struct = parse_fields(cls, factory=field, recurse=recurse)
|
|
164
172
|
fields = flatten_fields(struct)
|
|
165
173
|
freeze = frozen or any(f.frozen for f in fields)
|
|
174
|
+
# validate settings and save fields/params
|
|
175
|
+
params = DataParams(init, repr, eq, order, unsafe_hash,
|
|
176
|
+
frozen, match_args, kw_only, slots, recurse, field)
|
|
177
|
+
if isdataclass:
|
|
178
|
+
ofields = getattr(cls, FIELD_ATTR)
|
|
179
|
+
oparams = getattr(cls, PARAMS_ATTR)
|
|
180
|
+
# ensure there are no frozen conflicts
|
|
181
|
+
if frozen and not (oparams.frozen or all(f.frozen for f in ofields)):
|
|
182
|
+
raise TypeError(
|
|
183
|
+
'cannot inherit frozen dataclass from a non-frozen one')
|
|
184
|
+
if not frozen and (oparams.frozen or any(f.frozen for f in ofields)):
|
|
185
|
+
raise TypeError(
|
|
186
|
+
'cannot inherit non-frozen dataclass from a frozen one')
|
|
187
|
+
# ensure slots dont conflict with partially frozen dataclasses
|
|
188
|
+
if slots and not frozen and any(f.frozen for f in fields):
|
|
189
|
+
raise TypeError(
|
|
190
|
+
'cannot assign slots for partially frozen dataclass')
|
|
166
191
|
# assign fields to dataclass
|
|
167
192
|
setattr(cls, FIELD_ATTR, fields)
|
|
193
|
+
setattr(cls, PARAMS_ATTR, params)
|
|
168
194
|
# build functions
|
|
169
195
|
if init or init is None:
|
|
170
196
|
overwrite = init is True
|
|
@@ -186,7 +212,7 @@ def _process_class(
|
|
|
186
212
|
f'in class {cls.__name__}. Consider '
|
|
187
213
|
'using functools.total_ordering')
|
|
188
214
|
if freeze:
|
|
189
|
-
freeze_fields(cls,
|
|
215
|
+
freeze_fields(cls, fields, frozen)
|
|
190
216
|
# build hash function based on current state
|
|
191
217
|
class_dict = cls.__dict__
|
|
192
218
|
class_eq = class_dict.get('__eq__', None)
|
|
@@ -263,3 +289,50 @@ def dataclass(cls: Optional[TypeT] = None, *_, **kw) -> Union[TypeT, DataFunc]:
|
|
|
263
289
|
def wrapper(cls: TypeT) -> TypeT:
|
|
264
290
|
return _process_class(cls, **kw)
|
|
265
291
|
return wrapper if cls is None else wrapper(cls)
|
|
292
|
+
|
|
293
|
+
#** Classes **#
|
|
294
|
+
|
|
295
|
+
@runtime_checkable
|
|
296
|
+
class DataClassLike(Generic[F], Protocol):
|
|
297
|
+
"""Protocol for DataClass-Like Objects"""
|
|
298
|
+
__datafields__: List[F]
|
|
299
|
+
|
|
300
|
+
class DataParams:
|
|
301
|
+
"""Pseudo Dataclass to store parameters used to generate dataclass"""
|
|
302
|
+
__slots__ = (
|
|
303
|
+
'init',
|
|
304
|
+
'repr',
|
|
305
|
+
'eq',
|
|
306
|
+
'order',
|
|
307
|
+
'unsafe_hash',
|
|
308
|
+
'frozen',
|
|
309
|
+
'match_args',
|
|
310
|
+
'kw_only',
|
|
311
|
+
'slots',
|
|
312
|
+
'recurse',
|
|
313
|
+
'field')
|
|
314
|
+
|
|
315
|
+
def __init__(self,
|
|
316
|
+
init: Optional[bool],
|
|
317
|
+
repr: Optional[bool],
|
|
318
|
+
eq: bool,
|
|
319
|
+
order: bool,
|
|
320
|
+
unsafe_hash: bool,
|
|
321
|
+
frozen: bool,
|
|
322
|
+
match_args: bool,
|
|
323
|
+
kw_only: bool,
|
|
324
|
+
slots: bool,
|
|
325
|
+
recurse: bool,
|
|
326
|
+
field: Type[FieldDef],
|
|
327
|
+
):
|
|
328
|
+
self.init = init
|
|
329
|
+
self.repr = repr
|
|
330
|
+
self.eq = eq
|
|
331
|
+
self.order = order
|
|
332
|
+
self.unsafe_hash = unsafe_hash
|
|
333
|
+
self.frozen = frozen
|
|
334
|
+
self.match_args = match_args
|
|
335
|
+
self.kw_only = kw_only
|
|
336
|
+
self.slots = slots
|
|
337
|
+
self.recurse = recurse
|
|
338
|
+
self.field = field
|
|
@@ -4,6 +4,7 @@ DataClass Parsing Tools
|
|
|
4
4
|
from typing import Type, Optional, ClassVar, get_origin
|
|
5
5
|
|
|
6
6
|
from .abc import *
|
|
7
|
+
from .compat import is_stddataclass, convert_fields
|
|
7
8
|
|
|
8
9
|
#** Variables **#
|
|
9
10
|
__all__ = [
|
|
@@ -63,19 +64,24 @@ def parse_fields(
|
|
|
63
64
|
if recurse and hash(base) in COMPILED:
|
|
64
65
|
continue
|
|
65
66
|
COMPILED.add(hash(base))
|
|
67
|
+
# convert stdlib dataclass fields to valid class-struct
|
|
68
|
+
parent = getattr(base, DERIVE_ATTR, None)
|
|
69
|
+
if parent is None and is_stddataclass(base):
|
|
70
|
+
fields = convert_fields(base, ftype)
|
|
71
|
+
names = [f.name for f in fields]
|
|
72
|
+
parent = ClassStruct(names, {f.name:f for f in fields})
|
|
66
73
|
# process fields
|
|
67
|
-
parent = getattr(base, DERIVE_ATTR, None)
|
|
68
74
|
fields = ClassStruct(parent=parent)
|
|
69
75
|
annotations = getattr(base, '__annotations__', {})
|
|
70
76
|
for name, anno in annotations.items():
|
|
71
|
-
# retrieve default-value of variable (if exists)
|
|
72
|
-
default = getattr(base, name, MISSING)
|
|
73
|
-
if delete and hasattr(base, name):
|
|
74
|
-
delattr(base, name)
|
|
75
77
|
# handle ClassVar
|
|
76
78
|
if get_origin(anno) is ClassVar:
|
|
77
79
|
remove_field(fields, name)
|
|
78
80
|
continue
|
|
81
|
+
# retrieve default-value of variable (if exists)
|
|
82
|
+
default = getattr(base, name, MISSING)
|
|
83
|
+
if delete and hasattr(base, name):
|
|
84
|
+
delattr(base, name)
|
|
79
85
|
# preserve order of fields and add vardef
|
|
80
86
|
if name not in fields.order:
|
|
81
87
|
fields.order.append(name)
|
|
@@ -129,13 +135,16 @@ def flatten_fields(
|
|
|
129
135
|
heigharchy.insert(0, fields)
|
|
130
136
|
# sort fields
|
|
131
137
|
struct = FlatStruct()
|
|
132
|
-
kwargs =
|
|
138
|
+
kwargs = set() # track when kwargs have been spotted
|
|
133
139
|
for fields in heigharchy:
|
|
134
140
|
for name in fields.order:
|
|
135
141
|
field = fields.fields[name]
|
|
136
142
|
default = has_default(field)
|
|
137
|
-
kwargs = kwargs or (default and field.init and not field.kw_only)
|
|
138
143
|
missing = name not in struct.fields
|
|
144
|
+
if default and field.init and not field.kw_only:
|
|
145
|
+
kwargs.add(name)
|
|
146
|
+
elif name in kwargs:
|
|
147
|
+
kwargs.remove(name)
|
|
139
148
|
# raise error if non-kwarg found after kwargs start
|
|
140
149
|
if order_kw and kwargs and missing and not default:
|
|
141
150
|
raise TypeError(
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""
|
|
2
|
+
PyDerive DataClass UnitTests
|
|
3
|
+
"""
|
|
4
|
+
import unittest
|
|
5
|
+
import dataclasses
|
|
6
|
+
from typing import ClassVar, List
|
|
7
|
+
|
|
8
|
+
from ..dataclasses import *
|
|
9
|
+
|
|
10
|
+
#** Variables **#
|
|
11
|
+
__all__ = ['DataClassTests']
|
|
12
|
+
|
|
13
|
+
#** Classes **#
|
|
14
|
+
|
|
15
|
+
class DataClassTests(unittest.TestCase):
|
|
16
|
+
|
|
17
|
+
def test_initvar(self):
|
|
18
|
+
"""ensure InitVar works as intended"""
|
|
19
|
+
@dataclass
|
|
20
|
+
class T:
|
|
21
|
+
a: int
|
|
22
|
+
b: InitVar[int]
|
|
23
|
+
|
|
24
|
+
def __post_init__(self, b: int):
|
|
25
|
+
self.extra = b
|
|
26
|
+
t = T(1, 2)
|
|
27
|
+
self.assertEqual(t.a, 1)
|
|
28
|
+
self.assertFalse(hasattr(t, 'b'))
|
|
29
|
+
self.assertTrue(hasattr(t, 'extra'))
|
|
30
|
+
self.assertEqual(t.extra, 2)
|
|
31
|
+
|
|
32
|
+
def test_classvar(self):
|
|
33
|
+
"""ensure ClassVar works as intended"""
|
|
34
|
+
@dataclass
|
|
35
|
+
class T:
|
|
36
|
+
a: ClassVar[int] = 0
|
|
37
|
+
b: int
|
|
38
|
+
t = T(1)
|
|
39
|
+
self.assertEqual(t.b, 1)
|
|
40
|
+
self.assertNotIn('a', [f.name for f in fields(t)])
|
|
41
|
+
|
|
42
|
+
def test_compat(self):
|
|
43
|
+
"""validate backwards compatability w/ stdlib dataclasses"""
|
|
44
|
+
@dataclasses.dataclass
|
|
45
|
+
class Foo:
|
|
46
|
+
a: int
|
|
47
|
+
b: dataclasses.InitVar[int]
|
|
48
|
+
c: List[str] = dataclasses.field(default_factory=list, repr=False)
|
|
49
|
+
@dataclass
|
|
50
|
+
class Bar(Foo):
|
|
51
|
+
d: int = 0
|
|
52
|
+
def __post_init__(self, b: int):
|
|
53
|
+
self.extra = b
|
|
54
|
+
bar = Bar(1, 2, d=6)
|
|
55
|
+
self.assertEqual(bar.a, 1)
|
|
56
|
+
self.assertEqual(bar.d, 6)
|
|
57
|
+
self.assertListEqual(bar.c, [])
|
|
58
|
+
self.assertTrue(hasattr(bar, 'extra'))
|
|
59
|
+
self.assertEqual(bar.extra, 2)
|
|
60
|
+
|
|
61
|
+
def test_frozen(self):
|
|
62
|
+
"""validate frozen attribute works"""
|
|
63
|
+
@dataclass
|
|
64
|
+
class Foo:
|
|
65
|
+
a: int = 0
|
|
66
|
+
@dataclass
|
|
67
|
+
class Bar(Foo):
|
|
68
|
+
a: int
|
|
69
|
+
b: int = field(default=1, frozen=True)
|
|
70
|
+
bar = Bar(1, 2)
|
|
71
|
+
bar.a = 3
|
|
72
|
+
self.assertRaises(FrozenInstanceError, bar.__setattr__, 'b', 4)
|
|
73
|
+
|
|
74
|
+
def test_frozen_inherit(self):
|
|
75
|
+
"""ensure frozen inherrit fails when baseclass not frozen"""
|
|
76
|
+
@dataclass
|
|
77
|
+
class Foo:
|
|
78
|
+
a: int = 0
|
|
79
|
+
class Bar(Foo):
|
|
80
|
+
b: int = field(default=1, frozen=True)
|
|
81
|
+
self.assertRaises(TypeError, dataclass, Bar, frozen=True)
|
|
82
|
+
|
|
83
|
+
def test_asdict(self):
|
|
84
|
+
"""ensure asdict function as intended"""
|
|
85
|
+
@dataclass
|
|
86
|
+
class Foo:
|
|
87
|
+
a: int = 0
|
|
88
|
+
@dataclass
|
|
89
|
+
class Bar:
|
|
90
|
+
foo: Foo
|
|
91
|
+
b: int = 1
|
|
92
|
+
c: List[str] = field(default_factory=list)
|
|
93
|
+
b = Bar(Foo(1), 2)
|
|
94
|
+
self.assertDictEqual(asdict(b), {'foo': {'a': 1}, 'b': 2, 'c': []})
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: pyderive3
|
|
3
|
-
Version: 0.0.
|
|
3
|
+
Version: 0.0.3
|
|
4
4
|
Summary: Python3 Custom Data Class Helpers
|
|
5
5
|
Home-page: https://github.com/imgurbot12/pyderive
|
|
6
6
|
Author: Andrew Scott
|
|
@@ -88,6 +88,41 @@ for f in fields(foo):
|
|
|
88
88
|
print(f.name, f.custom_attr)
|
|
89
89
|
```
|
|
90
90
|
|
|
91
|
+
###### Backwards Compatibility
|
|
92
|
+
```python
|
|
93
|
+
import pyderive
|
|
94
|
+
import dataclasses
|
|
95
|
+
|
|
96
|
+
@dataclasses.dataclass
|
|
97
|
+
class Foo:
|
|
98
|
+
a: int
|
|
99
|
+
b: int = dataclasses.field(repr=False)
|
|
100
|
+
|
|
101
|
+
@pyderive.dataclass
|
|
102
|
+
class Bar(Foo):
|
|
103
|
+
c: int = pyderive.field(frozen=True)
|
|
104
|
+
|
|
105
|
+
f = Bar(1, 2, 3)
|
|
106
|
+
print(f)
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
###### Monkey Patching
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
from pyderive import compat
|
|
113
|
+
compat.monkey_patch()
|
|
114
|
+
|
|
115
|
+
from dataclasses import dataclass, field
|
|
116
|
+
|
|
117
|
+
@dataclass
|
|
118
|
+
class Foo:
|
|
119
|
+
a: int
|
|
120
|
+
b: int = field(frozen=True)
|
|
121
|
+
|
|
122
|
+
f = Foo(1, 2)
|
|
123
|
+
print(f)
|
|
124
|
+
```
|
|
125
|
+
|
|
91
126
|
##### Low Level Dataclass Compilation Tools
|
|
92
127
|
|
|
93
128
|
```python
|
|
@@ -2,9 +2,12 @@ README.md
|
|
|
2
2
|
setup.py
|
|
3
3
|
pyderive/__init__.py
|
|
4
4
|
pyderive/abc.py
|
|
5
|
+
pyderive/compat.py
|
|
5
6
|
pyderive/compile.py
|
|
6
|
-
pyderive/
|
|
7
|
+
pyderive/dataclasses.py
|
|
7
8
|
pyderive/parse.py
|
|
9
|
+
pyderive/tests/__init__.py
|
|
10
|
+
pyderive/tests/dataclasses.py
|
|
8
11
|
pyderive3.egg-info/PKG-INFO
|
|
9
12
|
pyderive3.egg-info/SOURCES.txt
|
|
10
13
|
pyderive3.egg-info/dependency_links.txt
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|