reslot 0.1__tar.gz → 0.7__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.7/PKG-INFO ADDED
@@ -0,0 +1,60 @@
1
+ Metadata-Version: 2.4
2
+ Name: reslot
3
+ Version: 0.7
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
+ ```
reslot-0.7/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,13 +1,18 @@
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.7"
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",
@@ -17,4 +22,4 @@ classifiers = [
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.7
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
+ ```
reslot-0.7/reslot.py ADDED
@@ -0,0 +1,109 @@
1
+ import builtins
2
+ from collections.abc import MutableMapping
3
+ from functools import wraps, cached_property
4
+ from inspect import getclasstree, getdoc
5
+ from typing import TypeVar, Iterator, Type, Optional, Set, Tuple
6
+
7
+ _UNSET = object()
8
+
9
+ _T = TypeVar("_T")
10
+
11
+
12
+ def collect_all_slots(cls) -> Set[str]:
13
+ def recurse(l):
14
+ if isinstance(l, type):
15
+ yield l
16
+ elif isinstance(l, tuple):
17
+ yield l[0]
18
+ yield from map(recurse, l[1])
19
+ else:
20
+ for ll in l:
21
+ yield from recurse(ll)
22
+
23
+ slots = set()
24
+ if hasattr(cls, "__slots__"):
25
+ slots.update(cls.__slots__)
26
+ for clls in recurse(getclasstree([cls])):
27
+ if hasattr(clls, "__slots__"):
28
+ slots.update(clls.__slots__)
29
+ return slots
30
+
31
+
32
+ def iter_needed_slots(cls: Type) -> Iterator[Tuple[str, str]]:
33
+ for attr in dir(cls):
34
+ try:
35
+ val = getattr(cls, attr)
36
+ except AttributeError:
37
+ continue
38
+ if not isinstance(val, cached_property):
39
+ continue
40
+ if val.attrname is None:
41
+ raise TypeError("cached_property without name")
42
+ yield val.attrname, getdoc(val.func)
43
+
44
+ def reslot(
45
+ cls: Optional[Type[_T]] = None,
46
+ ) -> Type[_T]:
47
+ """Class decorator to enable ``@cached_property`` with ``__slots__``
48
+
49
+ The decorated class needs a ``__dict__`` slot, but we won't put an actual
50
+ dictionary in it. Instead, we'll put a mapping with the needed slots in it.
51
+ """
52
+
53
+ def really_reslot(cls: Type[_T]) -> Type[_T]:
54
+ if not hasattr(cls, "__slots__"):
55
+ raise TypeError("Class doesn't have __slots__")
56
+ slots = collect_all_slots(cls)
57
+ if "__dict__" not in slots:
58
+ raise TypeError("Need __dict__ slot")
59
+
60
+ class SlotRedirector(MutableMapping, dict):
61
+ # I think inheriting from dict means we still have an empty
62
+ # dictionary floating in memory for each SlotRedirector instantiated.
63
+ # That's eighty bytes we don't need...but at least it doesn't grow.
64
+ __slots__ = dict(iter_needed_slots(cls))
65
+
66
+ def __setitem__(self, key, value, /):
67
+ try:
68
+ setattr(self, key, value)
69
+ except AttributeError:
70
+ raise KeyError("No such slot", key) from None
71
+
72
+ def __delitem__(self, key, /):
73
+ try:
74
+ delattr(self, key)
75
+ except AttributeError:
76
+ raise KeyError("Slot not set", key)
77
+
78
+ def __getitem__(self, key, /):
79
+ try:
80
+ return getattr(self, key)
81
+ except AttributeError:
82
+ raise KeyError("Slot not set", key)
83
+
84
+ def __len__(self):
85
+ return len(self.__slots__)
86
+
87
+ def __iter__(self):
88
+ return iter(self.__slots__)
89
+
90
+ if hasattr(cls, "__init__"):
91
+ core__init__ = cls.__init__
92
+
93
+ @wraps(core__init__)
94
+ def __init__(self, *args, **kwargs):
95
+ self.__dict__ = SlotRedirector()
96
+ core__init__(self, *args, **kwargs)
97
+
98
+ cls.__init__ = __init__
99
+ else:
100
+ def __init__(self, *args, **kwargs):
101
+ self.__dict__ = SlotRedirector()
102
+ super(cls, self).__init__(*args, **kwargs)
103
+
104
+ cls.__init__ = __init__
105
+ return cls
106
+
107
+ if cls is None:
108
+ return really_reslot
109
+ return really_reslot(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