reslot 0.8__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.
@@ -0,0 +1,60 @@
1
+ Metadata-Version: 2.4
2
+ Name: reslot
3
+ Version: 0.8
4
+ Summary: Class decorator to enable @cached_property on classes with __slots__
5
+ Author-email: Zachary Spector <public@zacharyspector.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://codeberg.org/clayote/reslot
8
+ Project-URL: Bug tracker, https://codeberg.org/clayote/reslot/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Topic :: Software Development :: Libraries
12
+ Classifier: Development Status :: 2 - Pre-Alpha
13
+ Requires-Python: ~=3.8
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Dynamic: license-file
17
+
18
+ # reslot
19
+
20
+
21
+ A class decorator that lets you use `@cached_property` on classes with `__slots__`.
22
+
23
+ The decorated class needs a `__dict__` slot, but there won't exactly be a
24
+ dictionary in it. Instead, `@reslot` will give it a custom `MutableMapping`
25
+ with *its own* slots. `@cached_property` will keep its cache there.
26
+
27
+ The custom `MutableMapping`'s slots will be exactly the slots needed to store
28
+ the results of every `@cached_property` that was on the class at the time it
29
+ was declared. This minimizes the memory footprint and makes lookup speedy.
30
+
31
+
32
+ ## Usage
33
+
34
+ ```python
35
+ from functools import cached_property
36
+
37
+ from reslot import reslot
38
+
39
+ BEANED = False
40
+
41
+ @reslot
42
+ class Spam:
43
+ __slots__ = ("__dict__",)
44
+
45
+ @cached_property
46
+ def eggs(self):
47
+ return {"delicious": False}
48
+
49
+ @cached_property
50
+ def beans(self):
51
+ global BEANED
52
+ BEANED = True
53
+ return {"spam": 111000, "delicious": True}
54
+
55
+ spam = Spam()
56
+ print(spam.eggs) # {"delicious": False}
57
+ print(BEANED) # False
58
+ print(spam.beans) # {"spam": 111000, "delicious": True}
59
+ print(BEANED) # True
60
+ ```
@@ -0,0 +1,6 @@
1
+ reslot.py,sha256=ADYharQLBJp0LxXeT8weTJHnmRKT6BSbns6dCMLHrdk,3276
2
+ reslot-0.8.dist-info/licenses/LICENSE,sha256=VE4HyKmDTdoGsJpu9htwTVPwjgiQG6nI3yVBQxx9J9Y,1069
3
+ reslot-0.8.dist-info/METADATA,sha256=M4frA34YMWS_J-L5qJcyXCNrp5Q5zqek7DF7qc4XHog,1728
4
+ reslot-0.8.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
5
+ reslot-0.8.dist-info/top_level.txt,sha256=DxypSdTiydR9REd7AKh05-3uZVg44mK04CPNGLf9SrA,7
6
+ reslot-0.8.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,7 @@
1
+ Copyright 2025 Zachary Avram Spector
2
+
3
+ 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 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:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ 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 @@
1
+ reslot
reslot.py ADDED
@@ -0,0 +1,115 @@
1
+ from collections.abc import MutableMapping
2
+ from functools import wraps, cached_property, partial, update_wrapper
3
+ from inspect import getclasstree, getdoc
4
+ from typing import TypeVar, Iterator, Type, Optional, Set, Tuple, Union, List
5
+
6
+ _UNSET = object()
7
+
8
+ _T = TypeVar("_T")
9
+
10
+ walk_class_tree_hint = List[Union[Type, Tuple[Type, Type], "recurse_class_tree_hint"]]
11
+
12
+ def walk_class_tree(l: walk_class_tree_hint) -> Iterator[Type]:
13
+ if isinstance(l, type):
14
+ yield l
15
+ elif isinstance(l, tuple):
16
+ yield l[0]
17
+ if len(l) > 1:
18
+ yield from walk_class_tree(l[1])
19
+ else:
20
+ for ll in l:
21
+ yield from walk_class_tree(ll)
22
+
23
+ def collect_all_slots(cls) -> Set[str]:
24
+ slots = set()
25
+ if hasattr(cls, "__slots__"):
26
+ slots.update(cls.__slots__)
27
+ for clls in walk_class_tree(getclasstree([cls])):
28
+ if hasattr(clls, "__slots__"):
29
+ slots.update(clls.__slots__)
30
+ return slots
31
+
32
+
33
+ def iter_needed_slots(cls: Type) -> Iterator[Tuple[str, Optional[str]]]:
34
+ for clls in walk_class_tree([cls]):
35
+ for attr in dir(clls):
36
+ try:
37
+ val = getattr(clls, attr)
38
+ except AttributeError:
39
+ continue
40
+ if not isinstance(val, cached_property):
41
+ continue
42
+ if val.attrname is None:
43
+ raise TypeError("cached_property without name")
44
+ yield val.attrname, getdoc(val.func)
45
+
46
+
47
+ def init(slot_dict, core_init, self, *args, **kwargs):
48
+ class SlotRedirector(MutableMapping, dict):
49
+ # I think inheriting from dict means we still have an empty
50
+ # dictionary floating in memory for each SlotRedirector instantiated.
51
+ # That's eighty bytes we don't need...but at least it doesn't grow.
52
+ __slots__ = slot_dict
53
+
54
+ def __setitem__(self, key, value, /):
55
+ try:
56
+ setattr(self, key, value)
57
+ except AttributeError:
58
+ raise KeyError("No such slot", key) from None
59
+
60
+ def __delitem__(self, key, /):
61
+ try:
62
+ delattr(self, key)
63
+ except AttributeError:
64
+ raise KeyError("Slot not set", key)
65
+
66
+ def __getitem__(self, key, /):
67
+ try:
68
+ return getattr(self, key)
69
+ except AttributeError:
70
+ raise KeyError("Slot not set", key)
71
+
72
+ def __len__(self):
73
+ return len(self.__slots__)
74
+
75
+ def __iter__(self):
76
+ return iter(self.__slots__)
77
+ self.__dict__ = SlotRedirector()
78
+ if callable(core_init):
79
+ core_init(self, *args, **kwargs)
80
+ else:
81
+ super(type(self), self).__init__(*args, **kwargs)
82
+
83
+ def reslot(
84
+ cls: Optional[Type[_T]] = None,
85
+ ) -> Type[_T]:
86
+ """Class decorator to enable ``@cached_property`` with ``__slots__``
87
+
88
+ The decorated class needs a ``__dict__`` slot, but we won't put an actual
89
+ dictionary in it. Instead, we'll put a mapping with the needed slots in it.
90
+ """
91
+
92
+ def really_reslot(cls: Type[_T]) -> Type[_T]:
93
+ if not hasattr(cls, "__slots__"):
94
+ raise TypeError("Class doesn't have __slots__")
95
+ slots = collect_all_slots(cls)
96
+ if "__dict__" not in slots:
97
+ raise TypeError("Need __dict__ slot")
98
+ slot_dict = dict(iter_needed_slots(cls))
99
+ if hasattr(cls, "__slots__"):
100
+ if isinstance(cls.__slots__, dict):
101
+ slot_dict.update(cls.__slots__)
102
+ else:
103
+ for slot in cls.__slots__:
104
+ slot_dict[slot] = None
105
+ if hasattr(cls, "__init__"):
106
+ part = partial(init, slot_dict, cls.__init__)
107
+ update_wrapper(part, cls.__init__)
108
+ else:
109
+ part = partial(init, slot_dict, None)
110
+ cls.__init__ = part
111
+ return cls
112
+
113
+ if cls is None:
114
+ return really_reslot
115
+ return really_reslot(cls)