ducktools-classbuilder 0.5.1__py3-none-any.whl → 0.6.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of ducktools-classbuilder might be problematic. Click here for more details.

@@ -1,14 +1,19 @@
1
1
  import typing
2
+ from types import MappingProxyType
2
3
  from typing_extensions import dataclass_transform
3
4
 
4
5
  from collections.abc import Callable
5
6
 
6
7
  from . import (
7
- INTERNALS_DICT, NOTHING,
8
- Field, MethodMaker, SlotFields as SlotFields,
9
- builder, fieldclass, get_flags, get_fields, make_slot_gatherer
8
+ NOTHING,
9
+ Field,
10
+ GeneratedCode,
11
+ MethodMaker,
12
+ SlotMakerMeta,
10
13
  )
11
14
 
15
+ from . import SlotFields as SlotFields, KW_ONLY as KW_ONLY
16
+
12
17
  # noinspection PyUnresolvedReferences
13
18
  from . import _NothingType
14
19
 
@@ -17,27 +22,15 @@ PREFAB_INIT_FUNC: str
17
22
  PRE_INIT_FUNC: str
18
23
  POST_INIT_FUNC: str
19
24
 
20
-
21
- # noinspection PyPep8Naming
22
- class _KW_ONLY_TYPE:
23
- def __repr__(self) -> str: ...
24
-
25
- KW_ONLY: _KW_ONLY_TYPE
25
+ _CopiableMappings = dict[str, typing.Any] | MappingProxyType[str, typing.Any]
26
26
 
27
27
  class PrefabError(Exception): ...
28
28
 
29
29
  def get_attributes(cls: type) -> dict[str, Attribute]: ...
30
30
 
31
- def get_init_maker(*, init_name: str="__init__") -> MethodMaker: ...
32
-
33
- def get_repr_maker(*, recursion_safe: bool = False) -> MethodMaker: ...
34
-
35
- def get_eq_maker() -> MethodMaker: ...
36
-
37
- def get_iter_maker() -> MethodMaker: ...
38
-
39
- def get_asdict_maker() -> MethodMaker: ...
40
-
31
+ def init_generator(cls: type, funcname: str = "__init__") -> GeneratedCode: ...
32
+ def iter_generator(cls: type, funcname: str = "__iter__") -> GeneratedCode: ...
33
+ def as_dict_generator(cls: type, funcname: str = "as_dict") -> GeneratedCode: ...
41
34
 
42
35
  init_maker: MethodMaker
43
36
  prefab_init_maker: MethodMaker
@@ -50,13 +43,8 @@ asdict_maker: MethodMaker
50
43
  class Attribute(Field):
51
44
  __slots__: dict
52
45
 
53
- init: bool
54
- repr: bool
55
- compare: bool
56
46
  iter: bool
57
- kw_only: bool
58
47
  serialize: bool
59
- exclude_field: bool
60
48
 
61
49
  def __init__(
62
50
  self,
@@ -71,7 +59,6 @@ class Attribute(Field):
71
59
  iter: bool = True,
72
60
  kw_only: bool = False,
73
61
  serialize: bool = True,
74
- exclude_field: bool = False,
75
62
  ) -> None: ...
76
63
 
77
64
  def __repr__(self) -> str: ...
@@ -93,9 +80,7 @@ def attribute(
93
80
  exclude_field: bool = False,
94
81
  ) -> Attribute: ...
95
82
 
96
- def slot_prefab_gatherer(cls: type) -> tuple[dict[str, Attribute], dict[str, typing.Any]]: ...
97
-
98
- def attribute_gatherer(cls: type) -> tuple[dict[str, Attribute], dict[str, typing.Any]]: ...
83
+ def prefab_gatherer(cls_or_ns: type | MappingProxyType) -> tuple[dict[str, Attribute], dict[str, typing.Any]]: ...
99
84
 
100
85
  def _make_prefab(
101
86
  cls: type,
@@ -114,6 +99,23 @@ def _make_prefab(
114
99
 
115
100
  _T = typing.TypeVar("_T")
116
101
 
102
+ # noinspection PyUnresolvedReferences
103
+ @dataclass_transform(field_specifiers=(Attribute, attribute))
104
+ class Prefab(metaclass=SlotMakerMeta):
105
+ _meta_gatherer: Callable[[type | _CopiableMappings], tuple[dict[str, Field], dict[str, typing.Any]]]
106
+ def __init_subclass__(
107
+ cls,
108
+ init: bool = True,
109
+ repr: bool = True,
110
+ eq: bool = True,
111
+ iter: bool = False,
112
+ match_args: bool = True,
113
+ kw_only: bool = False,
114
+ frozen: bool = False,
115
+ dict_method: bool = False,
116
+ recursive_repr: bool = False,
117
+ ) -> None: ...
118
+
117
119
 
118
120
  # For some reason PyCharm can't see 'attribute'?!?
119
121
  # noinspection PyUnresolvedReferences
@@ -0,0 +1,318 @@
1
+ Metadata-Version: 2.1
2
+ Name: ducktools-classbuilder
3
+ Version: 0.6.1
4
+ Summary: Toolkit for creating class boilerplate generators
5
+ Author: David C Ellis
6
+ License: MIT License
7
+
8
+ Copyright (c) 2024 David C Ellis
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://github.com/davidcellis/ducktools-classbuilder
29
+ Classifier: Development Status :: 4 - Beta
30
+ Classifier: Programming Language :: Python :: 3.8
31
+ Classifier: Programming Language :: Python :: 3.9
32
+ Classifier: Programming Language :: Python :: 3.10
33
+ Classifier: Programming Language :: Python :: 3.11
34
+ Classifier: Programming Language :: Python :: 3.12
35
+ Classifier: Operating System :: OS Independent
36
+ Classifier: License :: OSI Approved :: MIT License
37
+ Requires-Python: >=3.8
38
+ Description-Content-Type: text/markdown
39
+ License-File: LICENSE.md
40
+ Provides-Extra: docs
41
+ Requires-Dist: sphinx ; extra == 'docs'
42
+ Requires-Dist: myst-parser ; extra == 'docs'
43
+ Requires-Dist: sphinx-rtd-theme ; extra == 'docs'
44
+ Provides-Extra: performance_tests
45
+ Requires-Dist: attrs ; extra == 'performance_tests'
46
+ Requires-Dist: pydantic ; extra == 'performance_tests'
47
+ Provides-Extra: testing
48
+ Requires-Dist: pytest ; extra == 'testing'
49
+ Requires-Dist: pytest-cov ; extra == 'testing'
50
+ Requires-Dist: mypy ; extra == 'testing'
51
+ Requires-Dist: typing-extensions ; extra == 'testing'
52
+
53
+ # Ducktools: Class Builder #
54
+
55
+ `ducktools-classbuilder` is *the* Python package that will bring you the **joy**
56
+ of writing... functions... that will bring back the **joy** of writing classes.
57
+
58
+ Maybe.
59
+
60
+ While `attrs` and `dataclasses` are class boilerplate generators,
61
+ `ducktools.classbuilder` is intended to provide the tools to help make a customized
62
+ version of the same concept.
63
+
64
+ Install from PyPI with:
65
+ `python -m pip install ducktools-classbuilder`
66
+
67
+ ## Included Implementations ##
68
+
69
+ There are 2 different implementations provided with the module each of which offers
70
+ a subclass based and decorator based option.
71
+
72
+ > [!TIP]
73
+ > For more information on using these tools to create your own implementations
74
+ > using the builder see
75
+ > [the tutorial](https://ducktools-classbuilder.readthedocs.io/en/latest/tutorial.html)
76
+ > for a full tutorial and
77
+ > [extension_examples](https://ducktools-classbuilder.readthedocs.io/en/latest/extension_examples.html)
78
+ > for other customizations.
79
+
80
+ ### Core ###
81
+
82
+ These tools are available from the main `ducktools.classbuilder` module.
83
+
84
+ * `@slotclass`
85
+ * A decorator based implementation that uses a special dict subclass assigned
86
+ to `__slots__` to describe the fields for method generation.
87
+ * `AnnotationClass`
88
+ * A subclass based implementation that works with `__slots__`, type annotations
89
+ or `Field(...)` attributes to describe the fields for method generation.
90
+ * If `__slots__` isn't used to declare fields, it will be generated by a metaclass.
91
+
92
+ Each of these forms of class generation will result in the same methods being
93
+ attached to the class after the field information has been obtained.
94
+
95
+ ```python
96
+ from ducktools.classbuilder import Field, SlotFields, slotclass
97
+
98
+ @slotclass
99
+ class SlottedDC:
100
+ __slots__ = SlotFields(
101
+ the_answer=42,
102
+ the_question=Field(
103
+ default="What do you get if you multiply six by nine?",
104
+ doc="Life, the Universe, and Everything",
105
+ ),
106
+ )
107
+
108
+ ex = SlottedDC()
109
+ print(ex)
110
+ ```
111
+
112
+ ### Prefab ###
113
+
114
+ This is available from the `ducktools.classbuilder.prefab` submodule.
115
+
116
+ This includes more customization including `__prefab_pre_init__` and `__prefab_post_init__`
117
+ functions for subclass customization.
118
+
119
+ A `@prefab` decorator and `Prefab` base class are provided.
120
+ Similar to `AnnotationClass`, `Prefab` will generate `__slots__` by default.
121
+ However decorated classes with `@prefab` that do not declare fields using `__slots__`
122
+ will **not** be slotted and there is no `slots` argument to apply this.
123
+
124
+ Here is an example of applying a conversion in `__post_init__`:
125
+ ```python
126
+ from pathlib import Path
127
+ from ducktools.classbuilder.prefab import Prefab
128
+
129
+ class AppDetails(Prefab, frozen=True):
130
+ app_name: str
131
+ app_path: Path
132
+
133
+ def __prefab_post_init__(self, app_path: str | Path):
134
+ # frozen in `Prefab` is implemented as a 'set-once' __setattr__ function.
135
+ # So we do not need to use `object.__setattr__` here
136
+ self.app_path = Path(app_path)
137
+
138
+ steam = AppDetails(
139
+ "Steam",
140
+ r"C:\Program Files (x86)\Steam\steam.exe"
141
+ )
142
+
143
+ print(steam)
144
+ ```
145
+
146
+
147
+ ## What is the issue with generating `__slots__` with a decorator ##
148
+
149
+ If you want to use `__slots__` in order to save memory you have to declare
150
+ them when the class is originally created as you can't add them later.
151
+
152
+ When you use `@dataclass(slots=True)`[^2] with `dataclasses`, the function
153
+ has to make a new class and attempt to copy over everything from the original.
154
+
155
+ This is because decorators operate on classes *after they have been created*
156
+ while slots need to be declared beforehand.
157
+ While you can change the value of `__slots__` after a class has been created,
158
+ this will have no effect on the internal structure of the class.
159
+
160
+ By using a metaclass or by declaring fields using `__slots__` however,
161
+ the fields can be set *before* the class is constructed, so the class
162
+ will work correctly without needing to be rebuilt.
163
+
164
+ For example these two classes would be roughly equivalent, except that
165
+ `@dataclass` has had to recreate the class from scratch while `AnnotationClass`
166
+ has created `__slots__` and added the methods on to the original class.
167
+ This means that any references stored to the original class *before*
168
+ `@dataclass` has rebuilt the class will not be pointing towards the
169
+ correct class.
170
+
171
+ Here's a demonstration of the issue using a registry for serialization
172
+ functions.
173
+
174
+ > This example requires Python 3.10 or later as earlier versions of
175
+ > `dataclasses` did not support the `slots` argument.
176
+
177
+ ```python
178
+ import json
179
+ from dataclasses import dataclass
180
+ from ducktools.classbuilder import AnnotationClass, Field
181
+
182
+
183
+ class _RegisterDescriptor:
184
+ def __init__(self, func, registry):
185
+ self.func = func
186
+ self.registry = registry
187
+
188
+ def __set_name__(self, owner, name):
189
+ self.registry.register(owner, self.func)
190
+ setattr(owner, name, self.func)
191
+
192
+
193
+ class SerializeRegister:
194
+ def __init__(self):
195
+ self.serializers = {}
196
+
197
+ def register(self, cls, func):
198
+ self.serializers[cls] = func
199
+
200
+ def register_method(self, method):
201
+ return _RegisterDescriptor(method, self)
202
+
203
+ def default(self, o):
204
+ try:
205
+ return self.serializers[type(o)](o)
206
+ except KeyError:
207
+ raise TypeError(f"Object of type {type(o).__name__} is not JSON serializable")
208
+
209
+
210
+ register = SerializeRegister()
211
+
212
+
213
+ @dataclass(slots=True)
214
+ class DataCoords:
215
+ x: float = 0.0
216
+ y: float = 0.0
217
+
218
+ @register.register_method
219
+ def to_json(self):
220
+ return {"x": self.x, "y": self.y}
221
+
222
+
223
+ # slots=True is the default for AnnotationClass
224
+ class BuilderCoords(AnnotationClass, slots=True):
225
+ x: float = 0.0
226
+ y: float = Field(default=0.0, doc="y coordinate")
227
+
228
+ @register.register_method
229
+ def to_json(self):
230
+ return {"x": self.x, "y": self.y}
231
+
232
+
233
+ # In both cases __slots__ have been defined
234
+ print(f"{DataCoords.__slots__ = }")
235
+ print(f"{BuilderCoords.__slots__ = }\n")
236
+
237
+ data_ex = DataCoords()
238
+ builder_ex = BuilderCoords()
239
+
240
+ objs = [data_ex, builder_ex]
241
+
242
+ print(data_ex)
243
+ print(builder_ex)
244
+ print()
245
+
246
+ # Demonstrate you can not set values not defined in slots
247
+ for obj in objs:
248
+ try:
249
+ obj.z = 1.0
250
+ except AttributeError as e:
251
+ print(e)
252
+ print()
253
+
254
+ print("Attempt to serialize:")
255
+ for obj in objs:
256
+ try:
257
+ print(f"{type(obj).__name__}: {json.dumps(obj, default=register.default)}")
258
+ except TypeError as e:
259
+ print(f"{type(obj).__name__}: {e!r}")
260
+ ```
261
+
262
+ Output (Python 3.12):
263
+ ```
264
+ DataCoords.__slots__ = ('x', 'y')
265
+ BuilderCoords.__slots__ = {'x': None, 'y': 'y coordinate'}
266
+
267
+ DataCoords(x=0.0, y=0.0)
268
+ BuilderCoords(x=0.0, y=0.0)
269
+
270
+ 'DataCoords' object has no attribute 'z'
271
+ 'BuilderCoords' object has no attribute 'z'
272
+
273
+ Attempt to serialize:
274
+ DataCoords: TypeError('Object of type DataCoords is not JSON serializable')
275
+ BuilderCoords: {"x": 0.0, "y": 0.0}
276
+ ```
277
+
278
+ ## What features does this have? ##
279
+
280
+ Included as an example implementation, the `slotclass` generator supports
281
+ `default_factory` for creating mutable defaults like lists, dicts etc.
282
+ It also supports default values that are not builtins (try this on
283
+ [Cluegen](https://github.com/dabeaz/cluegen)).
284
+
285
+ It will copy values provided as the `type` to `Field` into the
286
+ `__annotations__` dictionary of the class.
287
+ Values provided to `doc` will be placed in the final `__slots__`
288
+ field so they are present on the class if `help(...)` is called.
289
+
290
+ `AnnotationClass` offers the same features with additional methods of gathering
291
+ fields.
292
+
293
+ If you want something with more features you can look at the `prefab`
294
+ submodule which provides more specific features that differ further from the
295
+ behaviour of `dataclasses`.
296
+
297
+ ## Will you add \<feature\> to `classbuilder.prefab`? ##
298
+
299
+ No. Not unless it's something I need or find interesting.
300
+
301
+ The original version of `prefab_classes` was intended to have every feature
302
+ anybody could possibly require, but this is no longer the case with this
303
+ rebuilt version.
304
+
305
+ I will fix bugs (assuming they're not actually intended behaviour).
306
+
307
+ However the whole goal of this module is if you want to have a class generator
308
+ with a specific feature, you can create or add it yourself.
309
+
310
+ ## Credit ##
311
+
312
+ Heavily inspired by [David Beazley's Cluegen](https://github.com/dabeaz/cluegen)
313
+
314
+ [^1]: `SlotFields` is actually just a subclassed `dict` with no changes. `__slots__`
315
+ works with dictionaries using the values of the keys, while fields are normally
316
+ used for documentation.
317
+
318
+ [^2]: or `@attrs.define`.
@@ -0,0 +1,12 @@
1
+ ducktools/classbuilder/__init__.py,sha256=i0NqVICBsMUBQtxX_2UsnETE9y0X15cwTSoSlE6_fJI,30820
2
+ ducktools/classbuilder/__init__.pyi,sha256=tdYtI5Wqn-iur-MGGSpk4EbQTtl91F_MOGHXwYf4BYo,7656
3
+ ducktools/classbuilder/annotations.py,sha256=17g1WnWfyMWBHKQp2HD_hvV-n7CKXy_zv8NTODpOsuU,5437
4
+ ducktools/classbuilder/annotations.pyi,sha256=cTZQ-pp2IkfdvwHiU3pIySUzzBKxfOtO-e5PkA8TNwo,520
5
+ ducktools/classbuilder/prefab.py,sha256=LCrnS2zKADX5FS0SdzCYLF4n5yR43CIlv2QLL6PDjl4,23292
6
+ ducktools/classbuilder/prefab.pyi,sha256=1YkrSSTcjzhNn_AXSYiGIaX7kLm3DFckCR_zytFp0PE,4307
7
+ ducktools/classbuilder/py.typed,sha256=la67KBlbjXN-_-DfGNcdOcjYumVpKG_Tkw-8n5dnGB4,8
8
+ ducktools_classbuilder-0.6.1.dist-info/LICENSE.md,sha256=6Thz9Dbw8R4fWInl6sGl8Rj3UnKnRbDwrc6jZerpugQ,1070
9
+ ducktools_classbuilder-0.6.1.dist-info/METADATA,sha256=7sRGN_m6jeEKYCdajAu8NN-7cs3U4E7s6YUdEj643m4,10911
10
+ ducktools_classbuilder-0.6.1.dist-info/WHEEL,sha256=cpQTJ5IWu9CdaPViMhC9YzF8gZuS5-vlfoFihTBC86A,91
11
+ ducktools_classbuilder-0.6.1.dist-info/top_level.txt,sha256=uSDLtio3ZFqdwcsMJ2O5yhjB4Q3ytbBWbA8rJREganc,10
12
+ ducktools_classbuilder-0.6.1.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: bdist_wheel (0.43.0)
2
+ Generator: setuptools (70.1.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5