reslot 0.1__tar.gz → 0.9__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.

Potentially problematic release.


This version of reslot might be problematic. Click here for more details.

reslot-0.9/PKG-INFO ADDED
@@ -0,0 +1,60 @@
1
+ Metadata-Version: 2.4
2
+ Name: reslot
3
+ Version: 0.9
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 :: 3 - 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
+ ```
reslot-0.9/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # reslot
2
+
3
+
4
+ A class decorator that lets you use `@cached_property` on classes with `__slots__`.
5
+
6
+ The decorated class needs a `__dict__` slot, but there won't exactly be a
7
+ dictionary in it. Instead, `@reslot` will give it a custom `MutableMapping`
8
+ with *its own* slots. `@cached_property` will keep its cache there.
9
+
10
+ The custom `MutableMapping`'s slots will be exactly the slots needed to store
11
+ the results of every `@cached_property` that was on the class at the time it
12
+ was declared. This minimizes the memory footprint and makes lookup speedy.
13
+
14
+
15
+ ## Usage
16
+
17
+ ```python
18
+ from functools import cached_property
19
+
20
+ from reslot import reslot
21
+
22
+ BEANED = False
23
+
24
+ @reslot
25
+ class Spam:
26
+ __slots__ = ("__dict__",)
27
+
28
+ @cached_property
29
+ def eggs(self):
30
+ return {"delicious": False}
31
+
32
+ @cached_property
33
+ def beans(self):
34
+ global BEANED
35
+ BEANED = True
36
+ return {"spam": 111000, "delicious": True}
37
+
38
+ spam = Spam()
39
+ print(spam.eggs) # {"delicious": False}
40
+ print(BEANED) # False
41
+ print(spam.beans) # {"spam": 111000, "delicious": True}
42
+ print(BEANED) # True
43
+ ```
@@ -1,20 +1,25 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
1
5
  [project]
2
6
  name = "reslot"
3
- version = "0.1"
7
+ version = "0.9"
4
8
  authors = [
5
9
  {name="Zachary Spector",email="public@zacharyspector.com"},
6
10
  ]
7
11
  description="Class decorator to enable @cached_property on classes with __slots__"
12
+ readme = {file="README.md", content-type="text/markdown"}
8
13
  license = "MIT"
9
14
  license-files = ["LICENSE"]
10
- requires-python = "~=3.12"
15
+ requires-python = "~=3.8"
11
16
  classifiers = [
12
17
  "Programming Language :: Python :: 3",
13
18
  "Operating System :: OS Independent",
14
19
  "Topic :: Software Development :: Libraries",
15
- "Development Status :: 2 - Pre-Alpha"
20
+ "Development Status :: 3 - Alpha"
16
21
  ]
17
22
 
18
23
  [project.urls]
19
24
  "Homepage" = "https://codeberg.org/clayote/reslot"
20
- "Bug tracker" = "https://codeberg.org/clayote/reslot/issues"
25
+ "Bug tracker" = "https://codeberg.org/clayote/reslot/issues"
@@ -0,0 +1,60 @@
1
+ Metadata-Version: 2.4
2
+ Name: reslot
3
+ Version: 0.9
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 :: 3 - 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
+ ```
reslot-0.9/reslot.py ADDED
@@ -0,0 +1,109 @@
1
+ from collections.abc import MutableMapping
2
+ from functools import cached_property, partial, update_wrapper
3
+ from inspect import getclasstree, getdoc
4
+ from typing import (Callable, Dict, TypeVar, Iterator, Type, Optional, Set,
5
+ Tuple, Union, List)
6
+
7
+ _UNSET = object()
8
+
9
+ _T = TypeVar("_T")
10
+
11
+ walk_class_tree_hint = List[Union[Type, Tuple[Type, Type], "walk_class_tree_hint"]]
12
+
13
+ def walk_class_tree(l: walk_class_tree_hint) -> Iterator[Type]:
14
+ if isinstance(l, type):
15
+ yield l
16
+ elif isinstance(l, tuple):
17
+ yield l[0]
18
+ if len(l) > 1:
19
+ yield from walk_class_tree(l[1])
20
+ else:
21
+ for ll in l:
22
+ yield from walk_class_tree(ll)
23
+
24
+ def collect_all_slots(cls: Type) -> Set[str]:
25
+ slots = set()
26
+ if hasattr(cls, "__slots__"):
27
+ slots.update(cls.__slots__)
28
+ for clls in walk_class_tree(getclasstree([cls])):
29
+ if hasattr(clls, "__slots__"):
30
+ slots.update(clls.__slots__)
31
+ return slots
32
+
33
+
34
+ def iter_needed_slots(cls: Type) -> Iterator[Tuple[str, Optional[str]]]:
35
+ for clls in walk_class_tree([cls]):
36
+ for attr in dir(clls):
37
+ try:
38
+ val = getattr(clls, attr)
39
+ except AttributeError:
40
+ continue
41
+ if not isinstance(val, cached_property):
42
+ continue
43
+ if val.attrname is None:
44
+ raise TypeError("cached_property without name")
45
+ yield val.attrname, getdoc(val.func)
46
+
47
+
48
+ def init(slot_dict: Dict[str, Optional[str]], core_init: Optional[Callable],
49
+ self, *args, **kwargs):
50
+ class SlotRedirector(MutableMapping, dict):
51
+ # I think inheriting from dict means we still have an empty
52
+ # dictionary floating in memory for each SlotRedirector instantiated.
53
+ # That's eighty bytes we don't need...but at least it doesn't grow.
54
+ __slots__ = slot_dict
55
+
56
+ def __setitem__(self, key, value, /):
57
+ try:
58
+ setattr(self, key, value)
59
+ except AttributeError:
60
+ raise KeyError("No such slot", key) from None
61
+
62
+ def __delitem__(self, key, /):
63
+ try:
64
+ delattr(self, key)
65
+ except AttributeError:
66
+ raise KeyError("Slot not set", key)
67
+
68
+ def __getitem__(self, key, /):
69
+ try:
70
+ return getattr(self, key)
71
+ except AttributeError:
72
+ raise KeyError("Slot not set", key)
73
+
74
+ def __len__(self):
75
+ return len(self.__slots__)
76
+
77
+ def __iter__(self):
78
+ return iter(self.__slots__)
79
+ self.__dict__ = SlotRedirector()
80
+ if callable(core_init):
81
+ core_init(self, *args, **kwargs)
82
+ else:
83
+ super(type(self), self).__init__(*args, **kwargs)
84
+
85
+ def reslot(cls: Type[_T]) -> 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
+ if not hasattr(cls, "__slots__"):
92
+ raise TypeError("Class doesn't have __slots__")
93
+ slots = collect_all_slots(cls)
94
+ if "__dict__" not in slots:
95
+ raise TypeError("Need __dict__ slot")
96
+ slot_dict = dict(iter_needed_slots(cls))
97
+ if hasattr(cls, "__slots__"):
98
+ if isinstance(cls.__slots__, dict):
99
+ slot_dict.update(cls.__slots__)
100
+ else:
101
+ for slot in cls.__slots__:
102
+ slot_dict[slot] = None
103
+ if hasattr(cls, "__init__"):
104
+ part = partial(init, slot_dict, cls.__init__)
105
+ update_wrapper(part, cls.__init__)
106
+ else:
107
+ part = partial(init, slot_dict, None)
108
+ cls.__init__ = part
109
+ return cls
reslot-0.1/PKG-INFO DELETED
@@ -1,15 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: reslot
3
- Version: 0.1
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.12
14
- License-File: LICENSE
15
- Dynamic: license-file
reslot-0.1/README.md DELETED
@@ -1,9 +0,0 @@
1
- # reslot
2
-
3
-
4
- A class decorator that lets you use `@cached_property` on classes with `__slots__`.
5
-
6
- The decorated class needs a `__dict__` slot, but there won't exactly be a
7
- dictionary in it. Instead, `@reslot` will give it a custom `MutableMapping`
8
- with *its own* slots. `@cached_property` will keep its cache there.
9
-
@@ -1,15 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: reslot
3
- Version: 0.1
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.12
14
- License-File: LICENSE
15
- Dynamic: license-file
reslot-0.1/reslot.py DELETED
@@ -1,133 +0,0 @@
1
- from collections.abc import MutableMapping
2
- from functools import wraps, cached_property
3
- from inspect import getclasstree
4
- from typing import TypeVar
5
-
6
- _UNSET = object()
7
-
8
- _T = TypeVar("_T")
9
-
10
-
11
- def collect_all_slots(cls) -> set[str]:
12
- def recurse(l: list[type | tuple[type, type] | list]):
13
- if isinstance(l, type):
14
- yield l
15
- elif isinstance(l, tuple):
16
- yield l[0]
17
- else:
18
- for ll in l:
19
- yield from recurse(ll)
20
-
21
- slots = set()
22
- if hasattr(cls, "__slots__"):
23
- slots.update(cls.__slots__)
24
- for clls in recurse(getclasstree([cls])):
25
- if hasattr(clls, "__slots__"):
26
- slots.update(clls.__slots__)
27
- return slots
28
-
29
-
30
- def surround_name(prefix: str | None, name: str, suffix: str | None) -> str:
31
- if prefix is None:
32
- if name.startswith("_"):
33
- prefix = ""
34
- else:
35
- prefix = "_"
36
- if suffix is None:
37
- if prefix:
38
- suffix = ""
39
- else:
40
- suffix = "_"
41
- return prefix + name + suffix
42
-
43
-
44
- def reslot(
45
- cls: type[_T] | None = None,
46
- prefix: str | None = None,
47
- suffix: str | None = None,
48
- ) -> type[_T]:
49
- """Class decorator to enable ``@cached_property`` with ``__slots__``
50
-
51
- The decorated class needs a ``__dict__`` slot, but we won't put an actual
52
- dictionary in it. Instead, we'll put a mapping with the needed slots in it.
53
-
54
- :param cls: The class to enable ``@cached_property`` on. If left ``None``,
55
- a partial function will be returned, which may then be used as a
56
- decorator.
57
- :param prefix: String to put at the beginning of the slot name. Defaults
58
- to ``None``, in which case we'll prefix the slot name with an underscore
59
- unless it already starts with one. We won't default to a prefix then,
60
- because that would invoke name mangling.
61
- :param suffix: String to put at the end of the slot name. Defaults to
62
- ``None``, in which case we won't use a suffix, unless ``prefix`` is
63
- also ``None`` or the empty string, in which case the default suffix is
64
- ``"_"``.
65
-
66
- """
67
-
68
- def really_reslot(cls: type[_T]) -> type[_T]:
69
- if not hasattr(cls, "__slots__"):
70
- raise TypeError("Class doesn't have __slots__")
71
- slots = collect_all_slots(cls)
72
- if "__dict__" not in slots:
73
- raise TypeError("Need __dict__ slot")
74
- slots.remove("__dict__")
75
-
76
- class SlotRedirector(MutableMapping):
77
- __slots__ = slots
78
-
79
- def __setitem__(self, key, value, /):
80
- try:
81
- setattr(self, key, value)
82
- except AttributeError:
83
- raise KeyError("No such slot", key) from None
84
-
85
- def __delitem__(self, key, /):
86
- try:
87
- delattr(self, key)
88
- except AttributeError:
89
- raise KeyError("Slot not set", key)
90
-
91
- def __getitem__(self, key, /):
92
- try:
93
- return getattr(self, key)
94
- except AttributeError:
95
- raise KeyError("Slot not set", key)
96
-
97
- def __len__(self):
98
- return len(self.__slots__)
99
-
100
- def __iter__(self):
101
- return iter(self.__slots__)
102
-
103
- if hasattr(cls, "__getattr__"):
104
- core_getattr = cls.__getattr__
105
-
106
- @wraps(core_getattr)
107
- def __getattr__(self: _T, attr: str):
108
- if attr == "__dict__":
109
- val = getattr(super(cls, self), "__dict__", _UNSET)
110
- if val is _UNSET:
111
- val = SlotRedirector()
112
- setattr(self, "__dict__", val)
113
- return val
114
- return core_getattr(self, attr)
115
-
116
- cls.__getattr__ = __getattr__
117
- else:
118
-
119
- def __getattr__(self: _T, attr: str):
120
- if attr == "__dict__":
121
- val = getattr(super(cls, self), "__dict__", _UNSET)
122
- if val is _UNSET:
123
- val = SlotRedirector()
124
- setattr(self, "__dict__", val)
125
- return val
126
- return getattr(super(type(self), self), attr)
127
-
128
- cls.__getattr__ = __getattr__
129
- return cls
130
-
131
- if cls is None:
132
- return really_reslot
133
- return really_reslot(cls)
File without changes
File without changes
File without changes
File without changes