zstdlib 0.10.7__tar.gz → 0.10.8__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.
Files changed (44) hide show
  1. {zstdlib-0.10.7 → zstdlib-0.10.8}/PKG-INFO +3 -4
  2. {zstdlib-0.10.7 → zstdlib-0.10.8}/pyproject.toml +9 -5
  3. {zstdlib-0.10.7 → zstdlib-0.10.8}/tests/log/test_cute.py +12 -3
  4. {zstdlib-0.10.7 → zstdlib-0.10.8}/tests/log/test_trace.py +3 -3
  5. {zstdlib-0.10.7 → zstdlib-0.10.8}/tests/test_enum.py +3 -3
  6. {zstdlib-0.10.7 → zstdlib-0.10.8}/tests/test_io.py +8 -8
  7. zstdlib-0.10.8/tests/test_keyed_instance.py +304 -0
  8. {zstdlib-0.10.7 → zstdlib-0.10.8}/tests/test_prompt.py +8 -2
  9. {zstdlib-0.10.7 → zstdlib-0.10.8}/tests/test_singleton.py +7 -4
  10. {zstdlib-0.10.7 → zstdlib-0.10.8}/zstdlib/__init__.py +4 -1
  11. {zstdlib-0.10.7 → zstdlib-0.10.8}/zstdlib/ansi.py +3 -3
  12. {zstdlib-0.10.7 → zstdlib-0.10.8}/zstdlib/enum.py +6 -4
  13. {zstdlib-0.10.7 → zstdlib-0.10.8}/zstdlib/frozen.py +30 -19
  14. {zstdlib-0.10.7 → zstdlib-0.10.8}/zstdlib/io.py +28 -22
  15. zstdlib-0.10.8/zstdlib/keyed_instance.py +164 -0
  16. {zstdlib-0.10.7 → zstdlib-0.10.8}/zstdlib/lazy.py +2 -5
  17. {zstdlib-0.10.7 → zstdlib-0.10.8}/zstdlib/macos.py +3 -3
  18. {zstdlib-0.10.7 → zstdlib-0.10.8}/zstdlib/prompt.py +4 -1
  19. {zstdlib-0.10.7 → zstdlib-0.10.8}/zstdlib/signal_cm.py +2 -1
  20. {zstdlib-0.10.7 → zstdlib-0.10.8}/zstdlib/singleton.py +3 -5
  21. {zstdlib-0.10.7 → zstdlib-0.10.8}/zstdlib.egg-info/PKG-INFO +3 -4
  22. {zstdlib-0.10.7 → zstdlib-0.10.8}/zstdlib.egg-info/SOURCES.txt +2 -0
  23. {zstdlib-0.10.7 → zstdlib-0.10.8}/zstdlib.egg-info/requires.txt +1 -0
  24. {zstdlib-0.10.7 → zstdlib-0.10.8}/LICENSE +0 -0
  25. {zstdlib-0.10.7 → zstdlib-0.10.8}/README.md +0 -0
  26. {zstdlib-0.10.7 → zstdlib-0.10.8}/setup.cfg +0 -0
  27. {zstdlib-0.10.7 → zstdlib-0.10.8}/tests/__init__.py +0 -0
  28. {zstdlib-0.10.7 → zstdlib-0.10.8}/tests/log/__init__.py +0 -0
  29. {zstdlib-0.10.7 → zstdlib-0.10.8}/tests/log/base.py +0 -0
  30. {zstdlib-0.10.7 → zstdlib-0.10.8}/tests/test_ansi.py +0 -0
  31. {zstdlib-0.10.7 → zstdlib-0.10.8}/tests/test_exc_capture.py +0 -0
  32. {zstdlib-0.10.7 → zstdlib-0.10.8}/tests/test_frozen.py +0 -0
  33. {zstdlib-0.10.7 → zstdlib-0.10.8}/tests/test_hybridmethod.py +0 -0
  34. {zstdlib-0.10.7 → zstdlib-0.10.8}/tests/test_lazy.py +0 -0
  35. {zstdlib-0.10.7 → zstdlib-0.10.8}/tests/test_not_set.py +0 -0
  36. {zstdlib-0.10.7 → zstdlib-0.10.8}/zstdlib/exc_capture.py +0 -0
  37. {zstdlib-0.10.7 → zstdlib-0.10.8}/zstdlib/hybridmethod.py +0 -0
  38. {zstdlib-0.10.7 → zstdlib-0.10.8}/zstdlib/log/__init__.py +0 -0
  39. {zstdlib-0.10.7 → zstdlib-0.10.8}/zstdlib/log/cute.py +0 -0
  40. {zstdlib-0.10.7 → zstdlib-0.10.8}/zstdlib/log/trace.py +0 -0
  41. {zstdlib-0.10.7 → zstdlib-0.10.8}/zstdlib/not_set.py +0 -0
  42. {zstdlib-0.10.7 → zstdlib-0.10.8}/zstdlib/py.typed +0 -0
  43. {zstdlib-0.10.7 → zstdlib-0.10.8}/zstdlib.egg-info/dependency_links.txt +0 -0
  44. {zstdlib-0.10.7 → zstdlib-0.10.8}/zstdlib.egg-info/top_level.txt +0 -0
@@ -1,16 +1,15 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zstdlib
3
- Version: 0.10.7
3
+ Version: 0.10.8
4
4
  Summary: A set of useful python utilities
5
- License: GPLv3
5
+ License-Expression: GPL-3.0-only
6
6
  Project-URL: Homepage, https://github.com/zwimer/zstdlib
7
7
  Classifier: Programming Language :: Python :: 3
8
8
  Classifier: Programming Language :: Python :: 3.14
9
- Classifier: Development Status :: 5 - Production/Stable
10
- Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
11
9
  Requires-Python: >=3.14
12
10
  Description-Content-Type: text/markdown
13
11
  License-File: LICENSE
12
+ Requires-Dist: fasteners
14
13
  Requires-Dist: osascript2
15
14
  Dynamic: license-file
16
15
 
@@ -1,5 +1,5 @@
1
1
  [build-system]
2
- requires = ["setuptools>=61.2"]
2
+ requires = ["setuptools>=77"]
3
3
  build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
@@ -7,15 +7,15 @@ name = "zstdlib"
7
7
  classifiers = [
8
8
  "Programming Language :: Python :: 3",
9
9
  "Programming Language :: Python :: 3.14",
10
- "Development Status :: 5 - Production/Stable",
11
- "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
12
10
  ]
13
- license = {text = "GPLv3"}
11
+ license = "GPL-3.0-only"
12
+ license-files = ["LICENSE"]
14
13
  description = "A set of useful python utilities"
15
14
  urls = {Homepage = "https://github.com/zwimer/zstdlib"}
16
15
  requires-python = ">= 3.14"
17
16
  dynamic = ["version"]
18
17
  dependencies = [
18
+ "fasteners",
19
19
  "osascript2" # For macOS
20
20
  ]
21
21
 
@@ -25,7 +25,6 @@ content-type = "text/markdown"
25
25
 
26
26
  [tool.setuptools]
27
27
  include-package-data = true
28
- license-files = ["LICENSE"]
29
28
 
30
29
  [tool.setuptools.packages.find]
31
30
  namespaces = false
@@ -40,6 +39,7 @@ attr = "zstdlib.__version__"
40
39
 
41
40
  [tool.pylint.MASTER]
42
41
  ignore-paths = '^tests/.*$'
42
+ jobs = 0
43
43
  [tool.pylint."MESSAGES CONTROL"]
44
44
  disable = [
45
45
  "unnecessary-lambda-assignment",
@@ -50,6 +50,9 @@ disable = [
50
50
  "invalid-name"
51
51
  ]
52
52
 
53
+ [tool.mypy]
54
+ strict = true
55
+
53
56
  [tool.black]
54
57
  line-length = 110
55
58
  target-version = ["py314"]
@@ -63,6 +66,7 @@ ignore=[
63
66
  "E731",
64
67
  "I001",
65
68
  "PLR0913", "PLR2004",
69
+ "PYI025",
66
70
  "S101", "S603",
67
71
  "TID252",
68
72
  ]
@@ -69,7 +69,10 @@ class TestCuteFormatter(LeftBase, unittest.TestCase):
69
69
  for i in levels:
70
70
  log.log(i, msg)
71
71
  self.assertEqual(len(levels), len(self.messages[log]))
72
- l_name = lambda idx: self.messages[log][idx].split("|")[0].strip()
72
+
73
+ def l_name(idx: int) -> str:
74
+ return self.messages[log][idx].split("|")[0].strip()
75
+
73
76
  self.assertEqual(Color.dim("Level 5".ljust(8)), l_name(0))
74
77
  self.assertEqual("DEBUG", l_name(1))
75
78
  self.assertEqual(Color.blue("INFO".ljust(8)), l_name(2))
@@ -85,7 +88,10 @@ class TestCuteFormatter(LeftBase, unittest.TestCase):
85
88
  log.log(4, msg)
86
89
  log.log(5, msg)
87
90
  self.assertEqual(2, len(self.messages[log]))
88
- l_name = lambda idx: self.messages[log][idx].split("|")[0].strip()
91
+
92
+ def l_name(idx: int) -> str:
93
+ return self.messages[log][idx].split("|")[0].strip()
94
+
89
95
  self.assertEqual(Color.dim("Level 4".ljust(8)), l_name(0))
90
96
  self.assertEqual("Level 5", l_name(1))
91
97
 
@@ -96,7 +102,10 @@ class TestCuteFormatter(LeftBase, unittest.TestCase):
96
102
  log.log(14, msg)
97
103
  log.log(15, msg)
98
104
  self.assertEqual(2, len(self.messages[log]))
99
- l_name = lambda idx: self.messages[log][idx].split("|")[0].strip()
105
+
106
+ def l_name(idx: int) -> str:
107
+ return self.messages[log][idx].split("|")[0].strip()
108
+
100
109
  self.assertEqual("Level 14".ljust(8), l_name(0))
101
110
  self.assertEqual(Color.bright_red_bg_yellow("Level 15".ljust(8)), l_name(1))
102
111
 
@@ -42,15 +42,15 @@ class TestTrace(LeftBase, unittest.TestCase):
42
42
  self.assertTrue(hasattr(logging, "trace"))
43
43
  self.assertTrue(hasattr(logging.getLogger(), "trace"))
44
44
  self.assertEqual(logging.TRACE, 5)
45
- self.assertEqual(logging.getLevelName(logging.TRACE), "TRACE") # type: ignore[call-overload]
45
+ self.assertEqual(logging.getLevelName(logging.TRACE), "TRACE")
46
46
  # Root check
47
47
  with self.hijack("") as log:
48
48
  old = log.getEffectiveLevel()
49
49
  # pylint: disable-next=not-callable
50
- logging.trace("test1") # type: ignore[misc]
50
+ logging.trace("test1")
51
51
  log.setLevel(logging.DEBUG)
52
52
  # pylint: disable-next=not-callable
53
- logging.trace("test2") # type: ignore[misc]
53
+ logging.trace("test2")
54
54
  log.setLevel(old)
55
55
  self.assertEqual(self.messages[log], ["test1"])
56
56
  # Logger check
@@ -1,5 +1,5 @@
1
1
  # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring,unused-variable
2
- from typing import Self
2
+ from typing import Self, Any
3
3
  import unittest
4
4
 
5
5
  from zstdlib.enum import EnumType, Enum, entries, values, auto
@@ -25,7 +25,7 @@ class TestEnumType(unittest.TestCase):
25
25
  class ET1(metaclass=EnumType, dupes_ok=True):
26
26
  a: int = 5
27
27
  b: int = 5
28
- c: dict = {} # noqa: RUF012
28
+ c: dict[Any, Any] = {} # noqa: RUF012
29
29
 
30
30
  with self.assertRaises(ValueError):
31
31
 
@@ -36,7 +36,7 @@ class TestEnumType(unittest.TestCase):
36
36
  with self.assertRaises(TypeError):
37
37
 
38
38
  class ET3(metaclass=EnumType):
39
- a: dict = {} # noqa: RUF012
39
+ a: dict[Any, Any] = {} # noqa: RUF012
40
40
 
41
41
  def test_type_check(self) -> None:
42
42
  class ET1(metaclass=EnumType, type_check=set()):
@@ -5,7 +5,7 @@ import unittest
5
5
  from zstdlib.io import ProtectedFile, BinaryIO, TextIO, io
6
6
 
7
7
 
8
- class RamFile(tempfile.SpooledTemporaryFile):
8
+ class RamFile(tempfile.SpooledTemporaryFile[Any]):
9
9
  """A file-like object that stores its contents in memory."""
10
10
 
11
11
  rollover = NotImplemented # Disallow rollover
@@ -22,7 +22,7 @@ class RamFile(tempfile.SpooledTemporaryFile):
22
22
  class TestIO(unittest.TestCase):
23
23
 
24
24
  def test_init(self) -> None:
25
- with RamFile(mode="wb+") as fb, RamFile() as fs:
25
+ with RamFile(mode="w+b") as fb, RamFile() as fs:
26
26
  ts = TextIO(fs)
27
27
  tb = BinaryIO(fb)
28
28
  with self.assertRaises(TypeError):
@@ -44,7 +44,7 @@ class TestIO(unittest.TestCase):
44
44
  def test_unread(self) -> None:
45
45
  with RamFile() as raw:
46
46
  f = io(raw)
47
- f.unread("hello") # type: ignore[arg-type] # STF types as bytes regardless of mode :/
47
+ f.unread("hello")
48
48
  self.assertEqual("hello", f._buffer)
49
49
 
50
50
  def test_read(self) -> None:
@@ -55,18 +55,18 @@ class TestIO(unittest.TestCase):
55
55
  self.assertEqual("fo", f.read(2))
56
56
  self.assertEqual("o", f.read(1))
57
57
  # Test read of buffer
58
- f.unread("bar") # type: ignore[arg-type] # STF types as bytes regardless of mode :/
58
+ f.unread("bar")
59
59
  self.assertEqual("b", f.read(1))
60
60
  # Test read of file + buffer
61
- f.unread("foob") # type: ignore[arg-type] # STF types as bytes regardless of mode :/
61
+ f.unread("foob")
62
62
  self.assertEqual("foobar", f.read(6))
63
- f.unread("foobar") # type: ignore[arg-type] # STF types as bytes regardless of mode :/
63
+ f.unread("foobar")
64
64
  self.assertEqual("foobarbaz", f.read())
65
65
 
66
66
  def test_peek(self) -> None:
67
67
  with RamFile() as raw:
68
68
  f = io(raw)
69
- f.unread("foo") # type: ignore[arg-type] # STF types as bytes regardless of mode :/
69
+ f.unread("foo")
70
70
  # Test peek of buffer
71
71
  for i in range(3):
72
72
  self.assertEqual("fo", f.peek(2))
@@ -77,7 +77,7 @@ class TestIO(unittest.TestCase):
77
77
  self.assertEqual("ba", f.peek(2))
78
78
  self.assertEqual("bar", f.read())
79
79
  # Test peek of both
80
- f.unread("baz") # type: ignore[arg-type] # STF types as bytes regardless of mode :/
80
+ f.unread("baz")
81
81
  raw.load("qux")
82
82
  for i in range(3):
83
83
  for k in range(5):
@@ -0,0 +1,304 @@
1
+ # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
2
+ from collections.abc import Callable, Iterator
3
+ from dataclasses import dataclass, field
4
+ from threading import Thread, get_ident
5
+ from contextlib import contextmanager
6
+ import multiprocessing as mp
7
+ from typing import Any
8
+ import traceback
9
+ import unittest
10
+ import pickle # nosec B403
11
+ import time
12
+ import sys
13
+ import os
14
+
15
+ from zstdlib.keyed_instance import KeyedInstanceProcessError
16
+ from zstdlib import CircularConstructionError, KeyedInstance
17
+
18
+
19
+ class Nop:
20
+ def __init__(self, key: int, *_: object) -> None:
21
+ self.key = key
22
+
23
+
24
+ # For test cases involving forking
25
+
26
+
27
+ def nop() -> None:
28
+ pass
29
+
30
+
31
+ @contextmanager
32
+ def try_do(name: str, q: mp.Queue[str]) -> Iterator[None]:
33
+ try:
34
+ yield
35
+ except KeyedInstanceProcessError:
36
+ q.put("KIPE")
37
+ except Exception as e: # noqa: BLE001
38
+ traceback.print_exc()
39
+ q.put(f"{e.__class__.__name__}: {e.args[0]}")
40
+ else:
41
+ q.put(name)
42
+
43
+
44
+ def subprocess_fn(q: mp.Queue[str]) -> None:
45
+ def test4() -> None:
46
+ with try_do("os.fork", q):
47
+ if not os.fork(): # Child dies
48
+ sys.exit(0)
49
+ for i in ("fork", "spawn"):
50
+ with try_do(f"mp.{i}", q):
51
+ p = mp.get_context(i).Process(target=nop) # type: ignore[attr-defined]
52
+ p.start()
53
+ p.join(1)
54
+ if p.is_alive():
55
+ p.kill()
56
+ raise RuntimeError("Process had to be killed")
57
+
58
+ # Multiprocessing is allowed right now, these should work
59
+ test4()
60
+
61
+ # Define a subclass
62
+ class Foo(KeyedInstance, Nop):
63
+ pass
64
+
65
+ # No instances yet, still ok
66
+ test4()
67
+ _ = Foo(1)
68
+
69
+ # This should fail, except spawn
70
+ test4()
71
+
72
+
73
+ # Main test cases
74
+
75
+
76
+ class TestKeyedInstance(unittest.TestCase):
77
+
78
+ def test_subclass(self) -> None:
79
+
80
+ class Foo(KeyedInstance, Nop):
81
+ pass
82
+
83
+ class Sup:
84
+ pass
85
+
86
+ with self.assertRaises(TypeError):
87
+
88
+ class Bar1(Sup, Foo):
89
+ pass
90
+
91
+ with self.assertRaises(TypeError):
92
+
93
+ class Bar2(Foo, Sup):
94
+ pass
95
+
96
+ def test_key(self) -> None:
97
+
98
+ class Foo(KeyedInstance, Nop):
99
+ pass
100
+
101
+ class Bar(KeyedInstance, Nop):
102
+ pass
103
+
104
+ a1_1 = Foo(1)
105
+ a1_2 = Foo(1)
106
+ a1_3 = Foo(1, 6)
107
+ a2_1 = Foo(2)
108
+ b1_1 = Bar(1)
109
+ b1_2 = Bar(1)
110
+
111
+ self.assertIs(a1_1, a1_2)
112
+ self.assertIs(a1_1, a1_3)
113
+ self.assertIs(b1_1, b1_2)
114
+ self.assertIsNot(a1_1, a2_1)
115
+ self.assertIsNot(a1_1, b1_1)
116
+
117
+ def test_circular(self) -> None:
118
+
119
+ class ToZero(KeyedInstance):
120
+ def __init__(self, x: int) -> None:
121
+ assert 0 <= x < 10
122
+ if x > 0:
123
+ _ = type(self)(x - 1)
124
+
125
+ _ = ToZero(6)
126
+
127
+ class Crazy(KeyedInstance):
128
+ def __init__(self, b: bool) -> None:
129
+ self.same = type(self)(b) # Father is self, circle
130
+
131
+ with self.assertRaises(CircularConstructionError):
132
+ _ = Crazy(True)
133
+
134
+ class Crazy2(KeyedInstance):
135
+ def __init__(self, b: bool) -> None:
136
+ self.inverse = type(self)(not b) # Grandfather is self
137
+
138
+ with self.assertRaises(CircularConstructionError):
139
+ _ = Crazy2(True)
140
+
141
+ def test_multiproc(self) -> None:
142
+
143
+ class Foo(KeyedInstance, Nop):
144
+ pass
145
+
146
+ foo1 = Foo(1)
147
+ with self.assertRaises(TypeError):
148
+ _ = pickle.dumps(foo1)
149
+
150
+ # Run tests
151
+ q: mp.Queue[str] = mp.Queue()
152
+ p = mp.get_context("spawn").Process(target=subprocess_fn, args=(q,))
153
+ p.start()
154
+ p.join(10) # This should be rather instant, this is generous
155
+ alive = p.is_alive()
156
+ time.sleep(0.1) # Let everything flush to the queue, just in case
157
+ q.put("Alive" if alive else "Dead")
158
+ if alive:
159
+ p.kill()
160
+ q.put(str(p.exitcode))
161
+ fin = "queue done, shutdown"
162
+ q.put(fin) # Better than relying on Empty b/c queue pipe / caches aren't instant
163
+ time.sleep(0.1) # Let everything flush to the queue, just in case
164
+
165
+ # Check results
166
+ results: list[str] = []
167
+ while not results or results[-1] != fin:
168
+ results.append(q.get(timeout=3)) # Should be done nearly instantly
169
+ expected: list[str] = ["os.fork", "mp.fork", "mp.spawn"] * 2
170
+ expected += ["KIPE", "KIPE", "mp.spawn", "Dead", "0", fin]
171
+ self.assertEqual(results, expected)
172
+
173
+ def test_interthread(self) -> None:
174
+
175
+ scale: int = 4 # Higher runs faster, lower is more accurate
176
+ actions: list[Action] = []
177
+ type RV_T = C1 | C2 | Exception
178
+
179
+ @dataclass(frozen=True)
180
+ class Action:
181
+ msg: str
182
+ tid: int = field(default_factory=lambda: get_ident())
183
+ ts: float = field(default_factory=lambda: time.monotonic())
184
+
185
+ @staticmethod
186
+ def strs(x: list[Action]) -> list[str]:
187
+ start = x[0].ts
188
+ tids = list({i.tid for i in x})
189
+ return [f"{round(scale*(i.ts-start))} | Thread-{tids.index(i.tid)+1} | {i.msg}" for i in x]
190
+
191
+ def save_results(fn: Callable[[], C1 | C2], ret: list[RV_T]) -> None:
192
+ try:
193
+ ret.append(fn())
194
+ except Exception as e: # noqa: BLE001
195
+ ret.append(e)
196
+
197
+ def dispatch_functions(*fns: Callable[[], RV_T]) -> list[RV_T]:
198
+ assert fns
199
+ rv: list[list[RV_T]] = [[] for i in fns]
200
+ ts = [Thread(target=lambda y=i, z=k: save_results(y, z), daemon=True) for i, k in zip(fns, rv)]
201
+ for t in ts:
202
+ t.start()
203
+ time.sleep(2 / scale / len(fns))
204
+ end = time.monotonic() + 10 # Generous timeout
205
+ for t in ts:
206
+ t.join(max(0, end - time.monotonic()))
207
+ if any(i.is_alive() for i in ts):
208
+ raise RuntimeError("Threads did not die")
209
+ if any(len(i) != 1 for i in rv):
210
+ raise ValueError("dispatch_functions failed")
211
+ return [i[0] for i in rv]
212
+
213
+ class _Body:
214
+ def _init(self, other: type[C1 | C2], key: int, *nxt: int) -> Any:
215
+ name = f"{self.__class__.__name__}({key}), next={list(nxt)}"
216
+ actions.append(Action(f"{name} - start"))
217
+ time.sleep(2 / scale)
218
+ second = f"{other.__name__}({nxt[0]})" if nxt else "None"
219
+ try:
220
+ actions.append(Action(f"{name} - requesting {second}"))
221
+ if nxt:
222
+ _ = other(*nxt)
223
+ except:
224
+ actions.append(Action(f"{name} - err: {second}"))
225
+ raise
226
+ actions.append(Action(f"{name} - done"))
227
+
228
+ class C1(KeyedInstance, _Body):
229
+ def __init__(self, key: int, *nxt: int) -> None:
230
+ self._init(C2, key, *nxt)
231
+
232
+ class C2(KeyedInstance, _Body):
233
+ def __init__(self, key: int, *nxt: int) -> None:
234
+ self._init(C1, key, *nxt)
235
+
236
+ # Test circular dependency between threads
237
+ fail1, fail2 = dispatch_functions(lambda: C1(0, 0, 0), lambda: C2(0, 0))
238
+ expected: list[str] = [
239
+ "0 | Thread-1 | C1(0), next=[0, 0] - start",
240
+ "1 | Thread-2 | C2(0), next=[0] - start",
241
+ "2 | Thread-1 | C1(0), next=[0, 0] - requesting C2(0)", # Blocked by Thread-2
242
+ "3 | Thread-2 | C2(0), next=[0] - requesting C1(0)", # C2(0):T2 -> C1(0):T1 -> C2(0):T2, err
243
+ "3 | Thread-2 | C2(0), next=[0] - err: C1(0)", # T2 dies, releases C2(0)
244
+ "3 | Thread-1 | C2(0), next=[0] - start", # C1(0):T1 -> C2(0):T2 , ok
245
+ "5 | Thread-1 | C2(0), next=[0] - requesting C1(0)", # C1(0):T1 -> C2(0):T2 -> C1(0):T1, err
246
+ "5 | Thread-1 | C2(0), next=[0] - err: C1(0)", # T1 dies, releases C1(0)
247
+ "5 | Thread-1 | C1(0), next=[0, 0] - err: C2(0)", # release C2(0)
248
+ ]
249
+ self.assertEqual(Action.strs(actions), expected)
250
+ self.assertIsInstance(fail1, CircularConstructionError)
251
+ self.assertIsInstance(fail2, CircularConstructionError)
252
+ self.assertIsNot(fail1, fail2)
253
+
254
+ # Test simultaneous construction
255
+ actions.clear()
256
+ res = dispatch_functions(*[lambda i2=i: (C1, C2)[i2 % 2](i2 * 10, i2 * 10 + 1) for i in range(1, 4)])
257
+ expected = [
258
+ "0 | Thread-1 | C2(10), next=[11] - start",
259
+ "1 | Thread-2 | C1(20), next=[21] - start",
260
+ "1 | Thread-3 | C2(30), next=[31] - start",
261
+ "2 | Thread-1 | C2(10), next=[11] - requesting C1(11)",
262
+ "2 | Thread-1 | C1(11), next=[] - start",
263
+ "3 | Thread-2 | C1(20), next=[21] - requesting C2(21)",
264
+ "3 | Thread-2 | C2(21), next=[] - start",
265
+ "3 | Thread-3 | C2(30), next=[31] - requesting C1(31)",
266
+ "3 | Thread-3 | C1(31), next=[] - start",
267
+ "4 | Thread-1 | C1(11), next=[] - requesting None",
268
+ "4 | Thread-1 | C1(11), next=[] - done",
269
+ "4 | Thread-1 | C2(10), next=[11] - done",
270
+ "5 | Thread-2 | C2(21), next=[] - requesting None",
271
+ "5 | Thread-2 | C2(21), next=[] - done",
272
+ "5 | Thread-2 | C1(20), next=[21] - done",
273
+ "5 | Thread-3 | C1(31), next=[] - requesting None",
274
+ "5 | Thread-3 | C1(31), next=[] - done",
275
+ "5 | Thread-3 | C2(30), next=[31] - done",
276
+ ]
277
+ self.assertEqual(Action.strs(actions), expected)
278
+ for itr, i in enumerate(res):
279
+ self.assertIsInstance(i, (C2, C1)[itr % 2])
280
+
281
+ # Test dependent construction time
282
+ actions.clear()
283
+ rv1, rv2 = dispatch_functions(lambda: C1(0, 0), lambda: C2(0, 10, 20))
284
+ expected = [
285
+ "0 | Thread-1 | C1(0), next=[0] - start",
286
+ "1 | Thread-2 | C2(0), next=[10, 20] - start",
287
+ "2 | Thread-1 | C1(0), next=[0] - requesting C2(0)", # Wait until C2(0):T2 is one
288
+ "3 | Thread-2 | C2(0), next=[10, 20] - requesting C1(10)",
289
+ "3 | Thread-2 | C1(10), next=[20] - start",
290
+ "5 | Thread-2 | C1(10), next=[20] - requesting C2(20)",
291
+ "5 | Thread-2 | C2(20), next=[] - start",
292
+ "7 | Thread-2 | C2(20), next=[] - requesting None",
293
+ "7 | Thread-2 | C2(20), next=[] - done", # Release C2(0)
294
+ "7 | Thread-2 | C1(10), next=[20] - done",
295
+ "7 | Thread-2 | C2(0), next=[10, 20] - done",
296
+ "7 | Thread-1 | C1(0), next=[0] - done",
297
+ ]
298
+ self.assertEqual(Action.strs(actions), expected)
299
+ self.assertIs(rv1, C1(0))
300
+ self.assertIs(rv2, C2(0))
301
+
302
+
303
+ if __name__ == "__main__":
304
+ unittest.main()
@@ -1,11 +1,17 @@
1
1
  # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring,unused-variable
2
2
  from unittest.mock import MagicMock, patch
3
+ from typing import Any
3
4
  import unittest
4
5
 
5
6
  from zstdlib.prompt import prompt_until, prompt_for, yn_prompt
6
7
 
7
- mock_input = lambda *x: patch("builtins.input", side_effect=x)
8
- mock_print = lambda: patch("builtins.print")
8
+
9
+ def mock_input(*x: str | type[BaseException]) -> Any:
10
+ return patch("builtins.input", side_effect=x)
11
+
12
+
13
+ def mock_print() -> Any:
14
+ return patch("builtins.print")
9
15
 
10
16
 
11
17
  def want_have(mock_p: MagicMock, msg: str, n: int) -> tuple[list[str], list[str]]:
@@ -63,15 +63,18 @@ class TestSingleton(unittest.TestCase):
63
63
  results = []
64
64
 
65
65
  # Helper functions that can help define thread tests
66
- timestamp = lambda: (datetime.now() - start[0]).total_seconds()
66
+ def timestamp() -> float:
67
+ return (datetime.now() - start[0]).total_seconds()
67
68
 
68
69
  def mk_cls(cls: type, name: str) -> None:
69
- fmt = lambda x: f"{timestamp():.1f}: {name} {x} {cls.__name__}()"
70
+ def fmt(x: str) -> str:
71
+ return f"{timestamp():.1f}: {name} {x} {cls.__name__}()"
72
+
70
73
  events.append(fmt("->"))
71
74
  results.append(cls())
72
75
  events.append(fmt("<-"))
73
76
 
74
- def simple(name: str, cls: type, delay: float) -> Callable:
77
+ def simple(name: str, cls: type, delay: float) -> Callable[[], None]:
75
78
  def _t() -> None:
76
79
  with lock: # Ensure all threads can start simultaneously
77
80
  pass
@@ -81,7 +84,7 @@ class TestSingleton(unittest.TestCase):
81
84
  return _t
82
85
 
83
86
  # Run all functions
84
- def run_all(*funcs: Callable) -> None:
87
+ def run_all(*funcs: Callable[[], None]) -> None:
85
88
  ts = [Thread(target=i) for i in funcs]
86
89
  events.clear()
87
90
  results.clear()
@@ -1,5 +1,6 @@
1
- __version__ = "0.10.7"
1
+ __version__ = "0.10.8"
2
2
 
3
+ from .keyed_instance import CircularConstructionError, KeyedInstance
3
4
  from .prompt import prompt_until, prompt_for, yn_prompt
4
5
  from .exc_capture import ExcCapture, ExcDelay
5
6
  from .hybridmethod import hybridmethod
@@ -11,10 +12,12 @@ from .enum import Enum, auto
11
12
  from . import macos, lazy, log, io
12
13
 
13
14
  __all__ = (
15
+ "CircularConstructionError",
14
16
  "Enum",
15
17
  "ExcCapture",
16
18
  "ExcDelay",
17
19
  "Freezable",
20
+ "KeyedInstance",
18
21
  "NotSet",
19
22
  "NotSetType",
20
23
  "Singleton",
@@ -1,6 +1,6 @@
1
1
  from enum import Enum, unique, auto
2
+ from typing import Self, cast
2
3
  from functools import cache
3
- from typing import Self
4
4
  import re
5
5
 
6
6
  MODIFIERS = ("bold", "dim", "italic", "underline", "blinking", "inverse", "hidden", "strikethrough")
@@ -68,9 +68,9 @@ class RawColor:
68
68
  class _ColorMeta(type):
69
69
  """A metaclass that implements __getattr__ at the class level for Color"""
70
70
 
71
- def __getattr__(cls, item: str) -> Color:
71
+ def __getattr__(cls: _ColorMeta, item: str) -> Color:
72
72
  try:
73
- return cls(code=RawColor._parse_color(item))
73
+ return cast(type[Color], cls)(code=RawColor._parse_color(item))
74
74
  except ValueError as e:
75
75
  raise AttributeError(str(e)) from e
76
76
 
@@ -1,5 +1,5 @@
1
+ from collections.abc import Iterator, Set
1
2
  from typing import ClassVar, Never, Any
2
- from collections.abc import Iterator
3
3
  import annotationlib
4
4
 
5
5
 
@@ -22,7 +22,9 @@ class EnumType(type):
22
22
 
23
23
  _AUTO_PREFIX = "Enum_Auto_"
24
24
  __entries__: dict[str, tuple[type | None, Any]] # Set by __new__ in attrs
25
- _TC_DEFAULT: ClassVar[set[type | None]] = {int, str, float, bool, complex, bytes, None, type(None)}
25
+ _TC_DEFAULT: ClassVar[frozenset[type | None]] = frozenset(
26
+ (int, str, float, bool, complex, bytes, None, type(None))
27
+ )
26
28
 
27
29
  class _AutoValue:
28
30
  """A class representing an automatically assigned enum value"""
@@ -39,7 +41,7 @@ class EnumType(type):
39
41
  @classmethod
40
42
  def _gen_entries_and_annotations(
41
43
  mcs: type[EnumType],
42
- attrs: dict,
44
+ attrs: dict[str, Any],
43
45
  dupes_ok: bool,
44
46
  ans: dict[str, type | None],
45
47
  ) -> dict[str, tuple[type | None, Any]]:
@@ -85,7 +87,7 @@ class EnumType(type):
85
87
  *,
86
88
  empty_ok: bool = False,
87
89
  dupes_ok: bool = False,
88
- type_check: set[type | None] = _TC_DEFAULT,
90
+ type_check: Set[type | None] = _TC_DEFAULT,
89
91
  **kwargs: Any,
90
92
  ) -> EnumType:
91
93
  # Disallow undesired instance methods
@@ -1,4 +1,4 @@
1
- from typing import Any, overload
1
+ from typing import Protocol, Any, overload
2
2
  from collections.abc import Callable
3
3
 
4
4
  _FN_ATTRS = (
@@ -62,18 +62,26 @@ class Freezable:
62
62
  super().__delattr__(item)
63
63
 
64
64
 
65
+ class _ClassDecorator(Protocol):
66
+ def __call__[T](self, cls: type[T], /) -> type[T]: ...
67
+
68
+
65
69
  @overload
66
- def frozen[T](arg: str) -> Callable[[type[T]], type[T]]: ...
70
+ def frozen(arg: str, /) -> _ClassDecorator: ...
71
+
72
+
67
73
  @overload
68
- def frozen[T](arg: type[T]) -> type[T]: ...
74
+ def frozen[T](arg: type[T], /) -> type[T]: ...
69
75
 
70
76
 
71
- def frozen[T](arg: str | type[T]) -> Callable[[type[T]], type[T]] | type[T]:
72
- """A class decorator to permanently freeze a class after some method, __init__ by default
73
- If passed a string, will freeze after the method with that name
77
+ def frozen(arg: str | type[Any], /) -> _ClassDecorator | type[Any]:
74
78
  """
79
+ A class decorator to permanently freeze a class after some method, __init__ by default
80
+ If passed a string, return a decorator that will freeze after the method with that name
81
+ """
82
+ ff_key: str = "_freezable_frozen_"
75
83
 
76
- def shim_method(cls: type, name: str, new: Callable) -> None:
84
+ def shim_method[T](cls: type[T], name: str, new: Callable[..., Any]) -> None:
77
85
  """Install shims for _FN_ATTRS; modifies new"""
78
86
  original = getattr(cls, name)
79
87
  for i in _FN_ATTRS: # Copy attributes of old fn onto new fn
@@ -81,24 +89,23 @@ def frozen[T](arg: str | type[T]) -> Callable[[type[T]], type[T]] | type[T]:
81
89
  setattr(new, i, getattr(original, i))
82
90
  setattr(cls, name, new) # Install
83
91
 
84
- def mk_frozen(cls: type, method: str) -> type:
85
- original_method: Callable = getattr(cls, method)
86
- original_setattr: Callable = cls.__setattr__
87
- original_delattr: Callable = cls.__delattr__
92
+ def mk_frozen[T](cls: type[T], method: str) -> type[T]:
93
+ original_method: Callable[..., Any] = getattr(cls, method)
94
+ original_setattr: Callable[[T, str, Any], None] = cls.__setattr__
95
+ original_delattr: Callable[[T, str], None] = cls.__delattr__
88
96
 
89
- def new_method(self: Any, *args: Any, **kwargs: Any) -> Any:
97
+ def new_method(self: T, *args: Any, **kwargs: Any) -> Any:
90
98
  ret = original_method(self, *args, **kwargs)
91
- # pylint: disable-next=protected-access
92
- self._freezable_frozen_ = True # type: ignore[attr-defined]
99
+ setattr(self, ff_key, True)
93
100
  return ret
94
101
 
95
- def __setattr__(self: Any, key: str, value: Any) -> Any:
96
- if getattr(self, "_freezable_frozen_", False):
102
+ def __setattr__(self: T, key: str, value: Any) -> None:
103
+ if getattr(self, ff_key, False):
97
104
  raise AttributeError("Cannot modify frozen object")
98
105
  return original_setattr(self, key, value)
99
106
 
100
- def __delattr__(self: Any, item: str) -> Any:
101
- if getattr(self, "_freezable_frozen_", False):
107
+ def __delattr__(self: T, item: str) -> None:
108
+ if getattr(self, ff_key, False):
102
109
  raise AttributeError("Cannot modify frozen object")
103
110
  return original_delattr(self, item)
104
111
 
@@ -109,5 +116,9 @@ def frozen[T](arg: str | type[T]) -> Callable[[type[T]], type[T]] | type[T]:
109
116
  return cls
110
117
 
111
118
  if isinstance(arg, str):
112
- return lambda cls: mk_frozen(cls, arg)
119
+
120
+ def decorator[T](cls: type[T]) -> type[T]:
121
+ return mk_frozen(cls, arg)
122
+
123
+ return decorator
113
124
  return mk_frozen(arg, "__init__")
@@ -1,13 +1,12 @@
1
- from io import BufferedIOBase, TextIOBase, RawIOBase, IOBase
1
+ from io import BufferedIOBase, TextIOBase, RawIOBase
2
+ from typing import Self, Any, IO, overload
2
3
  from weakref import WeakKeyDictionary
3
- from typing import Self, Any, cast
4
4
  from threading import RLock
5
- from itertools import chain
6
5
 
7
6
  __all__ = ("BinaryIO", "TextIO", "io")
8
7
 
9
8
 
10
- class ProtectedFile:
9
+ class ProtectedFile[T: (str, bytes)]:
11
10
  """A wrapper around an IO object that prevents access to certain attributes
12
11
  If absolutely necessary, users can access the raw object directly via .raw
13
12
  """
@@ -15,12 +14,12 @@ class ProtectedFile:
15
14
  PROTECTED_PREFIXES = ("read", "seek", "getbuffer", "getvalue", "detach")
16
15
  __slots__ = ("raw",)
17
16
 
18
- def __init__(self, raw: IOBase) -> None:
17
+ def __init__(self, raw: IO[T]) -> None:
19
18
  """Create a ProtectedFile
20
19
  Args:
21
20
  raw: The raw IO object to wrap, users can access it directly if they must
22
21
  """
23
- self.raw: IOBase = raw
22
+ self.raw: IO[T] = raw
24
23
 
25
24
  def __getattr__(self, item: str) -> Any:
26
25
  """Prevent access to certain attributes"""
@@ -39,17 +38,17 @@ class _IOWrapperBase[T: (str, bytes)]:
39
38
  """
40
39
 
41
40
  __slots__ = ("_buffer", "_eof", "f", "lock")
42
- _instances: WeakKeyDictionary[IOBase, Self] = WeakKeyDictionary() # noqa: RUF012
41
+ _instances: WeakKeyDictionary[IO[T], Self] = WeakKeyDictionary() # noqa: RUF012
43
42
  _wr_lock: RLock = RLock()
44
43
 
45
- def __new__(cls, f: IOBase) -> Self:
44
+ def __new__(cls, f: IO[T]) -> Self:
46
45
  """Create a new instance of cls for raw, or return an existing instance if one exists"""
47
46
  with cls._wr_lock:
48
47
  if (ret := cls._instances.get(f, None)) is None:
49
48
  cls._instances[f] = (ret := super().__new__(cls))
50
49
  return ret
51
50
 
52
- def __init__(self, f: IOBase, *, binary: bool) -> None:
51
+ def __init__(self, f: IO[T], *, binary: bool) -> None:
53
52
  """Initialize the IO object with a raw IO object
54
53
  Note: This class takes ownership of the input object, do not use it elsewhere
55
54
 
@@ -58,7 +57,7 @@ class _IOWrapperBase[T: (str, bytes)]:
58
57
  binary: If True, the IO object will read/write bytes, otherwise it will read/write strings
59
58
  """
60
59
  self._buffer: T = (bytes if binary else str)() # type: ignore[assignment]
61
- self.f = ProtectedFile(f)
60
+ self.f: ProtectedFile[T] = ProtectedFile(f)
62
61
  self.lock = RLock()
63
62
 
64
63
  def read(self, size: int = -1) -> T:
@@ -80,10 +79,10 @@ class _IOWrapperBase[T: (str, bytes)]:
80
79
  """
81
80
  with self.lock:
82
81
  nl: T = "\n" if isinstance(self._buffer, str) else b"\n"
83
- ret = self._read_buffer(self._buffer.find(nl)) + self._read_buffer(1)
82
+ ret: T = self._read_buffer(self._buffer.find(nl)) + self._read_buffer(1)
84
83
  if ret.endswith(nl):
85
84
  return ret
86
- return ret + cast(T, self.f.raw.readline()) # cast b/c IOBase's readline() -> bytes
85
+ return ret + self.f.raw.readline()
87
86
 
88
87
  def readlines(self) -> list[T]:
89
88
  """Read all lines from self.f.raw until EOF"""
@@ -137,8 +136,7 @@ class _IOWrapperBase[T: (str, bytes)]:
137
136
  #
138
137
 
139
138
  def _read(self, size: int) -> T:
140
- ret: T = cast(T, self.f.raw.read(size)) # cast b/c IOBase's read() -> bytes
141
- return ret if ret else self._buffer[:0] # Some .read's can return None
139
+ return ret if (ret := self.f.raw.read(size)) else self._buffer[:0] # .read can return None
142
140
 
143
141
  def _read_buffer(self, size: int = -1) -> T:
144
142
  if size == -1:
@@ -150,7 +148,7 @@ class _IOWrapperBase[T: (str, bytes)]:
150
148
  @staticmethod
151
149
  def _remainder(data: list[T], suffix: T) -> int:
152
150
  assert suffix, "suffix: expected non-empty str or bytes"
153
- rev = chain.from_iterable(reversed(i) for i in reversed(data))
151
+ rev = (j for it in map(reversed, reversed(data)) for j in it)
154
152
  for index, (i, k) in enumerate(zip(rev, reversed(suffix))):
155
153
  if i != k:
156
154
  return len(suffix) - index
@@ -167,7 +165,7 @@ class _IOWrapperBase[T: (str, bytes)]:
167
165
  __copy__ = None
168
166
 
169
167
 
170
- def _mode(f: IOBase, binary: bool | None) -> bool:
168
+ def _mode[T: (str, bytes)](f: IO[T], binary: bool | None) -> bool:
171
169
  """Attempt to determine if f is binary or not, if known what it should be, error if different"""
172
170
  mode = getattr(f, "mode", "")
173
171
  binary = binary or "b" in mode or isinstance(f, (RawIOBase, BufferedIOBase))
@@ -182,28 +180,36 @@ def _mode(f: IOBase, binary: bool | None) -> bool:
182
180
  class TextIO(_IOWrapperBase[str]):
183
181
  """A wrapper around TextIO objects that add additional functionality such as readuntil, unread, and peek"""
184
182
 
185
- def __new__(cls, f: IOBase) -> Self:
183
+ def __new__(cls, f: IO[str]) -> Self:
186
184
  if not _mode(f, False):
187
185
  raise TypeError("raw should be a non-binary IO object")
188
186
  return super().__new__(cls, f)
189
187
 
190
- def __init__(self, f: IOBase) -> None:
188
+ def __init__(self, f: IO[str]) -> None:
191
189
  super().__init__(f, binary=False)
192
190
 
193
191
 
194
192
  class BinaryIO(_IOWrapperBase[bytes]):
195
193
  """A wrapper around BinaryIO objects that add additional functionality such as readuntil, unread, and peek"""
196
194
 
197
- def __new__(cls, f: IOBase) -> Self:
195
+ def __new__(cls, f: IO[bytes]) -> Self:
198
196
  if _mode(f, True):
199
197
  raise TypeError("raw should be a binary IO object")
200
198
  return super().__new__(cls, f)
201
199
 
202
- def __init__(self, f: IOBase) -> None:
200
+ def __init__(self, f: IO[bytes]) -> None:
203
201
  super().__init__(f, binary=False)
204
202
 
205
203
 
206
- def io(raw: IOBase, binary: bool | None = None) -> TextIO | BinaryIO:
204
+ @overload
205
+ def io(raw: IO[str], binary: bool | None = None) -> TextIO: ...
206
+
207
+
208
+ @overload
209
+ def io(raw: IO[bytes], binary: bool | None = None) -> BinaryIO: ...
210
+
211
+
212
+ def io[T: (str, bytes)](raw: IO[T], binary: bool | None = None) -> TextIO | BinaryIO:
207
213
  """Convert an IO object to a TextIO or BinaryIO object
208
214
  For raw to be valid, one of the three must be true:
209
215
  1. raw is an io.TextIOBase, io.RawIOBase, or io.BufferedIOBase object
@@ -211,4 +217,4 @@ def io(raw: IOBase, binary: bool | None = None) -> TextIO | BinaryIO:
211
217
  3. binary must be set
212
218
  If the three detection methods disagree on if raw is binary, a TypeError is raised
213
219
  """
214
- return TextIO(raw) if _mode(raw, binary) else BinaryIO(raw)
220
+ return TextIO(raw) if _mode(raw, binary) else BinaryIO(raw) # type: ignore[arg-type]
@@ -0,0 +1,164 @@
1
+ from typing import Any, ClassVar, NamedTuple, Never, final, cast
2
+ from threading import Condition, Lock, get_ident
3
+ from collections.abc import Hashable
4
+ import sys
5
+
6
+ __all__ = ("CircularConstructionError", "KeyedInstance", "KeyedInstanceProcessError")
7
+
8
+
9
+ class CircularConstructionError(RuntimeError):
10
+ """Raised when keyed constructors form a circular dependency."""
11
+
12
+ def __init__(self, type_: type) -> None:
13
+ """type_ is the type that caused the circular dependency"""
14
+ super().__init__(f"Circular construction dependency for {type_.__qualname__}")
15
+
16
+
17
+ class _Constructing(NamedTuple): # An int that is not isinstance(int)
18
+ tid: int
19
+
20
+
21
+ @final
22
+ class _KeyedInstanceMeta(type):
23
+ """Metaclass implementing thread-safe keyed instance construction"""
24
+
25
+ type _InstanceKey = tuple[type[KeyedInstance], Hashable]
26
+ _instances: ClassVar[dict[_InstanceKey, KeyedInstance | _Constructing]] = {}
27
+ _waiting: ClassVar[dict[int, _InstanceKey]] = {}
28
+ _base_class: ClassVar[type[Any] | None] = None # KeyedInstance, after construction
29
+ _condition: ClassVar[Condition] = Condition(Lock())
30
+
31
+ def __new__(
32
+ mcs: type[_KeyedInstanceMeta],
33
+ name: str,
34
+ bases: tuple[type[Any], ...],
35
+ namespace: dict[str, Any],
36
+ **kwargs: Any,
37
+ ) -> type:
38
+ """Create KeyedInstance or a direct descendant."""
39
+ if mcs is not _KeyedInstanceMeta:
40
+ raise TypeError("_KeyedInstanceMeta cannot be subclassed")
41
+ # Ensure nothing is deriving KeyedInstance
42
+ root = mcs._base_class
43
+ if root is not None and (
44
+ not any(base is root for base in bases)
45
+ or any(isinstance(base, _KeyedInstanceMeta) and base is not root for base in bases)
46
+ ):
47
+ raise TypeError(f"{name} must directly inherit from KeyedInstance")
48
+ cls = type.__new__(mcs, name, bases, namespace, **kwargs)
49
+ # Lock in KeyedInstance as the base class as needed
50
+ if root is None:
51
+ mcs._base_class = cls
52
+ return cls
53
+
54
+ def __call__[T](cls: type[T], key: Hashable, *args: Any, **kwargs: Any) -> T:
55
+ """Return the instance cached under (cls, key), constructing it if needed."""
56
+ mcs = type(cls)
57
+ assert mcs is _KeyedInstanceMeta and issubclass(cls, KeyedInstance)
58
+ cache_key = (cast(type[KeyedInstance], cls), key)
59
+
60
+ # Lock-free fast path
61
+ instances = _KeyedInstanceMeta._instances
62
+ ret: KeyedInstance | _Constructing | None = instances.get(cache_key)
63
+ if ret is not None and not isinstance(ret, _Constructing):
64
+ return cast(T, ret)
65
+
66
+ construction_permission: _Constructing | None = None
67
+ waiting = _KeyedInstanceMeta._waiting
68
+ condition = _KeyedInstanceMeta._condition
69
+ tid: int = get_ident()
70
+ try:
71
+ while True: # Keep trying until some thread constructs the object
72
+ with condition:
73
+ ret = instances.get(cache_key)
74
+
75
+ # No thread is constructing this object, claim it
76
+ if ret is None:
77
+ instances[cache_key] = construction_permission = _Constructing(tid)
78
+ break
79
+
80
+ # The item has been constructed already, return it
81
+ if not isinstance(ret, _Constructing):
82
+ return cast(T, ret)
83
+
84
+ # Record the dependency and follow the wait-for chain.
85
+ try:
86
+ waiting[tid] = cache_key # Record we are waiting to construct this; safe b/c tid
87
+ blocking: int = ret.tid # Thread constructing what we want to return
88
+
89
+ # Trace blocking threads to ensure none are waiting on us
90
+ while blocking != tid:
91
+ dependency_key = waiting.get(blocking)
92
+ if dependency_key is None:
93
+ break
94
+ dependency = instances.get(dependency_key)
95
+ if not isinstance(dependency, _Constructing):
96
+ break
97
+ blocking = dependency.tid
98
+ else:
99
+ raise CircularConstructionError(cls)
100
+
101
+ # Wait for a thread to finish construction then recheck if we can start
102
+ condition.wait()
103
+ finally:
104
+ waiting.pop(tid, None)
105
+
106
+ # Construct the object finally then store the result
107
+ assert construction_permission is not None
108
+ ret = type.__call__(cls, key, *args, **kwargs)
109
+ assert isinstance(ret, KeyedInstance)
110
+ with condition:
111
+ instances[cache_key] = ret
112
+ condition.notify_all()
113
+ construction_permission = None # In case condition.__exit__ fails
114
+ return cast(T, ret)
115
+
116
+ except:
117
+ # Release the key on failed construction
118
+ if construction_permission is not None:
119
+ with condition:
120
+ if instances.get(cache_key) is construction_permission:
121
+ del instances[cache_key]
122
+ condition.notify_all()
123
+ raise
124
+
125
+
126
+ class KeyedInstance(metaclass=_KeyedInstanceMeta):
127
+ """Base class for instances cached by (concrete class, first argument).
128
+
129
+ Concrete subclasses must be final and directly inherit from this class.
130
+
131
+ The first argument is the cache key. Subsequent arguments
132
+ are used only during construction, not for cache identity.
133
+
134
+ The first thread to claim a cache key performs construction. If
135
+ construction fails, another waiting thread can attempt construction.
136
+
137
+ If items being constructed require constructing each other, a CircularConstructionError is raised
138
+
139
+ Do not mix this with fork / multiprocessing
140
+ """
141
+
142
+ def __reduce_ex__(self, *_: object) -> Never:
143
+ """Prevent usage in multiprocessing"""
144
+ raise TypeError(f"{type(self).__qualname__} instances cannot be pickled")
145
+
146
+
147
+ # Disallow mixing multiprocessing with KeyedInstance usage
148
+
149
+
150
+ class KeyedInstanceProcessError(RuntimeError):
151
+ """Raised when keyed instances are used with multiprocessing."""
152
+
153
+
154
+ def _check_fork(event: str, *_: Any) -> None:
155
+ if event not in {"os.fork", "os.forkpty"}:
156
+ return
157
+ # pylint: disable=protected-access
158
+ with _KeyedInstanceMeta._condition:
159
+ if _KeyedInstanceMeta._instances or _KeyedInstanceMeta._waiting: # Only raise if used
160
+ raise KeyedInstanceProcessError("Cannot fork after creating KeyedInstance instances")
161
+ # pylint: enable=protected-access
162
+
163
+
164
+ sys.addaudithook(_check_fork)
@@ -1,13 +1,10 @@
1
1
  from collections.abc import Callable
2
- from typing import ParamSpec
3
2
  from threading import Lock
4
3
 
5
- P = ParamSpec("P")
6
-
7
4
  __all__ = ("Func", "Str")
8
5
 
9
6
 
10
- class Func:
7
+ class Func[**P]:
11
8
  """A lazily evaluated function"""
12
9
 
13
10
  __slots__ = ("_args", "_fn", "_kwargs", "_lock", "_result")
@@ -31,7 +28,7 @@ class Func:
31
28
  return self._result
32
29
 
33
30
 
34
- class Str(Func):
31
+ class Str[**P](Func[P]):
35
32
  """A lazily evaluated string"""
36
33
 
37
34
  def __str__(self) -> str:
@@ -1,4 +1,4 @@
1
- from typing import NamedTuple, Final, ClassVar, Self
1
+ from typing import NamedTuple, Final, ClassVar, Self, Any
2
2
  from collections.abc import Callable, Iterable
3
3
  from subprocess import TimeoutExpired, Popen
4
4
  from multiprocessing import Process
@@ -32,7 +32,7 @@ class Caffeinate:
32
32
 
33
33
  class _Data(NamedTuple):
34
34
  owner: int
35
- proc: Popen
35
+ proc: Popen[Any]
36
36
 
37
37
  class SignalZeroError(ValueError):
38
38
  """Raised when calling __enter__ or __exit__ on a Caffeinate instance with .signal == 0"""
@@ -53,7 +53,7 @@ class Caffeinate:
53
53
  system: bool = False,
54
54
  user: bool = False,
55
55
  timeout: int | None = None,
56
- wait: int | Popen | Process | None = None,
56
+ wait: int | Popen[Any] | Process | None = None,
57
57
  # For Caffeinate class itself
58
58
  signal: Signals | int = Signals.SIGTERM,
59
59
  block: bool = False,
@@ -42,7 +42,10 @@ def prompt_until(
42
42
  If eof EOFError is caught, return None
43
43
  Return the case-adjusted string the user entered
44
44
  """
45
- cased = lambda x: (x.casefold() if ignore_case else x)
45
+
46
+ def cased(x: str) -> str:
47
+ return x.casefold() if ignore_case else x
48
+
46
49
  until = frozenset(map(cased, (until,) if isinstance(until, str) else until))
47
50
  try:
48
51
  while (ret := cased(input(msg).strip())) not in until:
@@ -1,13 +1,14 @@
1
1
  from collections.abc import Callable, Iterator
2
2
  from contextlib import contextmanager
3
3
  from logging import getLogger
4
+ from types import FrameType
4
5
  import signal
5
6
 
6
7
 
7
8
  @contextmanager
8
9
  def signal_cm(
9
10
  signalnum: signal.Signals | int,
10
- handler: signal.Handlers | Callable,
11
+ handler: signal.Handlers | Callable[[int, FrameType | None], None],
11
12
  *,
12
13
  disable_logging: bool = False,
13
14
  ) -> Iterator[None]:
@@ -1,10 +1,8 @@
1
- from typing import ClassVar, TypeVar, Never, Self, Any
1
+ from typing import ClassVar, Never, Any
2
2
  from collections import defaultdict
3
3
  from threading import RLock
4
4
  from functools import cache
5
5
 
6
- T = TypeVar("T")
7
-
8
6
 
9
7
  class NoInstanceError(TypeError):
10
8
  """A TypeError raised when trying to get a Singleton instance before constructing it"""
@@ -50,7 +48,7 @@ class _SingletonType(type):
50
48
 
51
49
  @classmethod
52
50
  @cache
53
- def instance(mcs, t: type[T]) -> T:
51
+ def instance(mcs, t: type[Singleton]) -> Singleton:
54
52
  """Get the instance of cls"""
55
53
  if not isinstance(t, mcs):
56
54
  raise TypeError(f"{t} is not a Singleton type")
@@ -66,7 +64,7 @@ class Singleton(metaclass=_SingletonType):
66
64
  """A thread-safe singleton base class"""
67
65
 
68
66
  @classmethod
69
- def instance(cls) -> Self:
67
+ def instance(cls) -> Singleton:
70
68
  """Blocking get the instance of cls; raise if not constructed"""
71
69
  assert isinstance(cls, _SingletonType), "Metaclass should be _SingletonType"
72
70
  tc: type[_SingletonType] = type(cls)
@@ -1,16 +1,15 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zstdlib
3
- Version: 0.10.7
3
+ Version: 0.10.8
4
4
  Summary: A set of useful python utilities
5
- License: GPLv3
5
+ License-Expression: GPL-3.0-only
6
6
  Project-URL: Homepage, https://github.com/zwimer/zstdlib
7
7
  Classifier: Programming Language :: Python :: 3
8
8
  Classifier: Programming Language :: Python :: 3.14
9
- Classifier: Development Status :: 5 - Production/Stable
10
- Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
11
9
  Requires-Python: >=3.14
12
10
  Description-Content-Type: text/markdown
13
11
  License-File: LICENSE
12
+ Requires-Dist: fasteners
14
13
  Requires-Dist: osascript2
15
14
  Dynamic: license-file
16
15
 
@@ -8,6 +8,7 @@ tests/test_exc_capture.py
8
8
  tests/test_frozen.py
9
9
  tests/test_hybridmethod.py
10
10
  tests/test_io.py
11
+ tests/test_keyed_instance.py
11
12
  tests/test_lazy.py
12
13
  tests/test_not_set.py
13
14
  tests/test_prompt.py
@@ -23,6 +24,7 @@ zstdlib/exc_capture.py
23
24
  zstdlib/frozen.py
24
25
  zstdlib/hybridmethod.py
25
26
  zstdlib/io.py
27
+ zstdlib/keyed_instance.py
26
28
  zstdlib/lazy.py
27
29
  zstdlib/macos.py
28
30
  zstdlib/not_set.py
@@ -1 +1,2 @@
1
+ fasteners
1
2
  osascript2
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes