zstdlib 0.10.4__tar.gz → 0.10.6__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 (42) hide show
  1. {zstdlib-0.10.4 → zstdlib-0.10.6}/PKG-INFO +1 -1
  2. zstdlib-0.10.6/tests/test_hybridmethod.py +37 -0
  3. zstdlib-0.10.6/tests/test_prompt.py +103 -0
  4. {zstdlib-0.10.4 → zstdlib-0.10.6}/zstdlib/__init__.py +6 -1
  5. zstdlib-0.10.6/zstdlib/hybridmethod.py +45 -0
  6. {zstdlib-0.10.4 → zstdlib-0.10.6}/zstdlib/macos.py +9 -12
  7. zstdlib-0.10.6/zstdlib/prompt.py +93 -0
  8. {zstdlib-0.10.4 → zstdlib-0.10.6}/zstdlib.egg-info/PKG-INFO +1 -1
  9. {zstdlib-0.10.4 → zstdlib-0.10.6}/zstdlib.egg-info/SOURCES.txt +4 -0
  10. {zstdlib-0.10.4 → zstdlib-0.10.6}/LICENSE +0 -0
  11. {zstdlib-0.10.4 → zstdlib-0.10.6}/README.md +0 -0
  12. {zstdlib-0.10.4 → zstdlib-0.10.6}/pyproject.toml +0 -0
  13. {zstdlib-0.10.4 → zstdlib-0.10.6}/setup.cfg +0 -0
  14. {zstdlib-0.10.4 → zstdlib-0.10.6}/tests/__init__.py +0 -0
  15. {zstdlib-0.10.4 → zstdlib-0.10.6}/tests/log/__init__.py +0 -0
  16. {zstdlib-0.10.4 → zstdlib-0.10.6}/tests/log/base.py +0 -0
  17. {zstdlib-0.10.4 → zstdlib-0.10.6}/tests/log/test_cute.py +0 -0
  18. {zstdlib-0.10.4 → zstdlib-0.10.6}/tests/log/test_trace.py +0 -0
  19. {zstdlib-0.10.4 → zstdlib-0.10.6}/tests/test_ansi.py +0 -0
  20. {zstdlib-0.10.4 → zstdlib-0.10.6}/tests/test_enum.py +0 -0
  21. {zstdlib-0.10.4 → zstdlib-0.10.6}/tests/test_exc_capture.py +0 -0
  22. {zstdlib-0.10.4 → zstdlib-0.10.6}/tests/test_frozen.py +0 -0
  23. {zstdlib-0.10.4 → zstdlib-0.10.6}/tests/test_io.py +0 -0
  24. {zstdlib-0.10.4 → zstdlib-0.10.6}/tests/test_lazy.py +0 -0
  25. {zstdlib-0.10.4 → zstdlib-0.10.6}/tests/test_not_set.py +0 -0
  26. {zstdlib-0.10.4 → zstdlib-0.10.6}/tests/test_singleton.py +0 -0
  27. {zstdlib-0.10.4 → zstdlib-0.10.6}/zstdlib/ansi.py +0 -0
  28. {zstdlib-0.10.4 → zstdlib-0.10.6}/zstdlib/enum.py +0 -0
  29. {zstdlib-0.10.4 → zstdlib-0.10.6}/zstdlib/exc_capture.py +0 -0
  30. {zstdlib-0.10.4 → zstdlib-0.10.6}/zstdlib/frozen.py +0 -0
  31. {zstdlib-0.10.4 → zstdlib-0.10.6}/zstdlib/io.py +0 -0
  32. {zstdlib-0.10.4 → zstdlib-0.10.6}/zstdlib/lazy.py +0 -0
  33. {zstdlib-0.10.4 → zstdlib-0.10.6}/zstdlib/log/__init__.py +0 -0
  34. {zstdlib-0.10.4 → zstdlib-0.10.6}/zstdlib/log/cute.py +0 -0
  35. {zstdlib-0.10.4 → zstdlib-0.10.6}/zstdlib/log/trace.py +0 -0
  36. {zstdlib-0.10.4 → zstdlib-0.10.6}/zstdlib/not_set.py +0 -0
  37. {zstdlib-0.10.4 → zstdlib-0.10.6}/zstdlib/py.typed +0 -0
  38. {zstdlib-0.10.4 → zstdlib-0.10.6}/zstdlib/signal_cm.py +0 -0
  39. {zstdlib-0.10.4 → zstdlib-0.10.6}/zstdlib/singleton.py +0 -0
  40. {zstdlib-0.10.4 → zstdlib-0.10.6}/zstdlib.egg-info/dependency_links.txt +0 -0
  41. {zstdlib-0.10.4 → zstdlib-0.10.6}/zstdlib.egg-info/requires.txt +0 -0
  42. {zstdlib-0.10.4 → zstdlib-0.10.6}/zstdlib.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zstdlib
3
- Version: 0.10.4
3
+ Version: 0.10.6
4
4
  Summary: A set of useful python utilities
5
5
  License: GPLv3
6
6
  Project-URL: Homepage, https://github.com/zwimer/zstdlib
@@ -0,0 +1,37 @@
1
+ # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring,unused-variable
2
+ from typing import ClassVar
3
+ import unittest
4
+
5
+ from zstdlib import hybridmethod
6
+
7
+
8
+ class TestHybridMethod(unittest.TestCase):
9
+
10
+ def test_hybridmethod(self) -> None:
11
+
12
+ class A:
13
+ objs: ClassVar[dict[int, A]] = {}
14
+
15
+ def __init__(self, x: int) -> None:
16
+ self.x: int = x
17
+ self.objs[x] = self
18
+
19
+ @hybridmethod
20
+ def get(self: A | None, cls: type[A], *, x: int | None = None) -> A:
21
+ if x is not None:
22
+ return cls.objs[x]
23
+ if self is None:
24
+ raise TypeError("Unable to determine x")
25
+ return cls.objs[self.x]
26
+
27
+ a = A(1)
28
+ b = A(2)
29
+ self.assertIsNot(a, b)
30
+ self.assertIs(a.get(), a)
31
+ self.assertIs(A.get(x=2), b)
32
+ with self.assertRaises(TypeError):
33
+ A.get()
34
+
35
+
36
+ if __name__ == "__main__":
37
+ unittest.main()
@@ -0,0 +1,103 @@
1
+ # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring,unused-variable
2
+ from unittest.mock import MagicMock, patch
3
+ import unittest
4
+
5
+ from zstdlib.prompt import prompt_until, prompt_for, yn_prompt
6
+
7
+
8
+ mock_input = lambda *x: patch("builtins.input", side_effect=x)
9
+ mock_print = lambda: patch("builtins.print")
10
+
11
+
12
+ def want_have(mock_p: MagicMock, msg: str, n: int) -> tuple[list[str], list[str]]:
13
+ if any(len(i.args) != 1 or i.kwargs for i in mock_p.call_args_list):
14
+ return False
15
+ return [i.args[0] for i in mock_p.call_args_list], [msg] * n
16
+
17
+
18
+ class TestPromptUntil(unittest.TestCase):
19
+ msg = "print_me"
20
+
21
+ def test_str(self) -> None:
22
+ with mock_print() as stdout, mock_input("test", "test", "A") as stdout:
23
+ self.assertEqual(prompt_until(self.msg, until="a"), "a")
24
+ self.assertEqual(*want_have(stdout, self.msg, 3))
25
+
26
+ def test_set(self) -> None:
27
+ with mock_print() as stdout, mock_input("test", "ab", "A") as stdout:
28
+ self.assertEqual(prompt_until(self.msg, until=("b", "a")), "a")
29
+ self.assertEqual(*want_have(stdout, self.msg, 3))
30
+
31
+ def test_case(self) -> None:
32
+ with mock_print() as stdout, mock_input("test", "test", "a", "A") as stdout:
33
+ self.assertEqual(prompt_until(self.msg, until="A", ignore_case=False), "A")
34
+ self.assertEqual(*want_have(stdout, self.msg, 4))
35
+
36
+ def test_eof(self) -> None:
37
+ with mock_print() as stdout, mock_input("test", EOFError) as stdout:
38
+ with self.assertRaises(EOFError):
39
+ prompt_until(self.msg, until="A")
40
+ self.assertEqual(*want_have(stdout, self.msg, 2))
41
+ with mock_print() as stdout, mock_input("test", EOFError) as stdout:
42
+ self.assertIs(prompt_until(self.msg, until="A", eof=True), None)
43
+ self.assertEqual(*want_have(stdout, self.msg, 2))
44
+
45
+ def test_ctrlc(self) -> None:
46
+ with mock_print() as stdout, mock_input("test", KeyboardInterrupt) as stdout:
47
+ with self.assertRaises(KeyboardInterrupt):
48
+ prompt_until(self.msg, until="A")
49
+ self.assertEqual(*want_have(stdout, self.msg, 2))
50
+ with mock_print() as stdout, mock_input("test", KeyboardInterrupt) as stdout:
51
+ self.assertIs(prompt_until(self.msg, until="A", ctrl_c=True), None)
52
+ self.assertEqual(*want_have(stdout, self.msg, 2))
53
+
54
+
55
+ class TestPromptFor(unittest.TestCase):
56
+ out = "Type continue "
57
+
58
+ def test_basic(self) -> None:
59
+ with mock_print() as stdout, mock_input("test", "test", "cOntinue") as stdout:
60
+ self.assertTrue(prompt_for())
61
+ self.assertEqual(*want_have(stdout, self.out, 3))
62
+
63
+ def test_eof(self) -> None:
64
+ with mock_print() as stdout, mock_input("test", EOFError) as stdout:
65
+ with self.assertRaises(EOFError):
66
+ prompt_for()
67
+ self.assertEqual(*want_have(stdout, self.out, 2))
68
+ with mock_print() as stdout, mock_input("test", EOFError) as stdout:
69
+ self.assertFalse(prompt_for(eof=True))
70
+ self.assertEqual(*want_have(stdout, self.out, 2))
71
+
72
+ class TestYNPrompt(unittest.TestCase):
73
+ out = "Yes or no? [yn] "
74
+
75
+ def test_basic(self) -> None:
76
+ with mock_print() as stdout, mock_input("test", "yes", "y") as stdout:
77
+ self.assertTrue(yn_prompt())
78
+ self.assertEqual(*want_have(stdout, self.out, 3))
79
+ with mock_print() as stdout, mock_input("test", "no", "n") as stdout:
80
+ self.assertIs(yn_prompt(), False)
81
+ self.assertEqual(*want_have(stdout, self.out, 3))
82
+
83
+ def test_yes_no(self) -> None:
84
+ out = "Yes or no? [yes/no] "
85
+ with mock_print() as stdout, mock_input("test", "y", "yes") as stdout:
86
+ self.assertTrue(yn_prompt(yes_no=True))
87
+ self.assertEqual(*want_have(stdout, out, 3))
88
+ with mock_print() as stdout, mock_input("test", "n", "no") as stdout:
89
+ self.assertFalse(yn_prompt(yes_no=True))
90
+ self.assertEqual(*want_have(stdout, out, 3))
91
+
92
+ def test_eof(self) -> None:
93
+ with mock_print() as stdout, mock_input("test", EOFError) as stdout:
94
+ with self.assertRaises(EOFError):
95
+ yn_prompt()
96
+ self.assertEqual(*want_have(stdout, self.out, 2))
97
+ with mock_print() as stdout, mock_input("test", EOFError) as stdout:
98
+ self.assertFalse(yn_prompt(eof=True))
99
+ self.assertEqual(*want_have(stdout, self.out, 2))
100
+
101
+
102
+ if __name__ == "__main__":
103
+ unittest.main()
@@ -1,6 +1,8 @@
1
- __version__ = "0.10.4"
1
+ __version__ = "0.10.6"
2
2
 
3
3
  from .exc_capture import ExcCapture, ExcDelay
4
+ from .prompt import prompt_for, yn_prompt
5
+ from .hybridmethod import hybridmethod
4
6
  from .not_set import NotSetType, NotSet
5
7
  from .frozen import Freezable, frozen
6
8
  from .singleton import Singleton
@@ -18,9 +20,12 @@ __all__ = (
18
20
  "Singleton",
19
21
  "auto",
20
22
  "frozen",
23
+ "hybridmethod",
21
24
  "io",
22
25
  "lazy",
23
26
  "log",
24
27
  "macos",
28
+ "prompt_for",
25
29
  "signal_cm",
30
+ "yn_prompt",
26
31
  )
@@ -0,0 +1,45 @@
1
+ from typing import Concatenate, overload
2
+ from collections.abc import Callable
3
+
4
+ __all__ = ("hybridmethod",)
5
+
6
+
7
+ type _HybridFunc[T, R, **P] = Callable[Concatenate[T | None, type[T], P], R]
8
+
9
+
10
+ class hybridmethod[T, R, **P]: # Name aligns with @staticmethod and such
11
+ """
12
+ A member function decorator that combines an instances bound function and @classmethod
13
+ If a member function uses @hybridmethod then it may use the signature:
14
+ @hybridmethod
15
+ def f(self: Self | None, cls: type[Self], ...)
16
+ This could be used to implement functions such as:
17
+ def history(self: Self | None, cls: type[Self], *, id: int | None = None): ...
18
+ ...
19
+ A.history(id=a.id)
20
+ A.history(id=0)
21
+ a.history()
22
+ """
23
+
24
+ __slots__ = ("_fn",)
25
+
26
+ def __init__(self, fn: _HybridFunc[T, R, P]) -> None:
27
+ self._fn: _HybridFunc[T, R, P] = fn
28
+
29
+ @overload
30
+ def __get__(self, instance: T, owner: type[T] | None = None, /) -> Callable[P, R]: ...
31
+
32
+ @overload
33
+ def __get__(self, instance: None, owner: type[T], /) -> Callable[P, R]: ...
34
+
35
+ def __get__(self, instance: T | None, owner: type[T] | None = None, /) -> Callable[P, R]:
36
+ if owner is None:
37
+ if instance is None:
38
+ raise TypeError("instance and owner should not both be None")
39
+ owner = type(instance)
40
+
41
+ # functools.partial doesn't preserve typing as we need it to :/
42
+ def ret(*args: P.args, **kwargs: P.kwargs) -> R:
43
+ return self._fn(instance, owner, *args, **kwargs)
44
+
45
+ return ret
@@ -1,4 +1,4 @@
1
- from typing import NamedTuple, ParamSpec, ClassVar, TypeVar, Self
1
+ from typing import NamedTuple, Final, ClassVar, Self
2
2
  from collections.abc import Callable, Iterable
3
3
  from subprocess import TimeoutExpired, Popen
4
4
  from multiprocessing import Process
@@ -17,15 +17,12 @@ __all__ = ("Caffeinate", "osascript")
17
17
 
18
18
  CAFFEINATE = Path("/usr/bin/caffeinate") # This is a hard-coded location on macOS
19
19
  KILL_WAIT_SECONDS: int = 60 # How long to .wait after .send_signal
20
- _CAFFEINATE_ENABLED = CAFFEINATE.exists()
21
-
22
- P = ParamSpec("P")
23
- R = TypeVar("R")
24
20
 
25
21
 
26
22
  class Caffeinate:
27
23
  """A small wrapper class around macOS' CLI tool Caffeinate"""
28
24
 
25
+ SUPPORTED: Final[ClassVar[bool]] = CAFFEINATE.exists()
29
26
  _finalizing: ClassVar[bool] = False
30
27
  _instances_lock: ClassVar[Lock] = Lock()
31
28
  _instances: ClassVar[set[Caffeinate]] = set() # Self makes mypy upset here; maybe b/c of subclassing? :/
@@ -57,7 +54,7 @@ class Caffeinate:
57
54
  user: bool = False,
58
55
  timeout: int | None = None,
59
56
  wait: int | Popen | Process | None = None,
60
- # For Caeffinate class itself
57
+ # For Caffeinate class itself
61
58
  signal: Signals | int = Signals.SIGTERM,
62
59
  block: bool = False,
63
60
  ) -> None:
@@ -76,13 +73,13 @@ class Caffeinate:
76
73
  disk: If True: Create an assertion to prevent the disk from idle sleeping.
77
74
  system: If True: Create an assertion to prevent the system from sleeping. This assertion is valid only when system is running on AC power.
78
75
  user: If True: Create an assertion to declare that user is active. If the display is off, this option turns the display on and prevents the display from going into idle sleep. If a timeout is not specified with '-t' option, then this assertion is taken with a default of 5 second timeout.
79
- timeout: Specifies the timeout value in seconds for which this assertion has to be valid. The assertion is dropped after the specified timeout. Timeout value is not used by the Caeffinate CLI when cmd is passed. Note: this timeout is passed to the Caffeinate CLI command, it is not enforced by python
80
- wait: Waits for the process with the specified pid to exit. Once the the process exits, the assertion is also released. This option is ignored by the Caeffinate CLI when cmd is passed.
76
+ timeout: Specifies the timeout value in seconds for which this assertion has to be valid. The assertion is dropped after the specified timeout. Timeout value is not used by the Caffeinate CLI when cmd is passed. Note: this timeout is passed to the Caffeinate CLI command, it is not enforced by python
77
+ wait: Waits for the process with the specified pid to exit. Once the the process exits, the assertion is also released. This option is ignored by the Caffeinate CLI when cmd is passed.
81
78
  This option conflicts with cmd.
82
79
  signal: The signal used to kill the child process (if cmd likely the process Caffeinate execs into). If 0, do not kill it
83
80
  block: If True: Block until cmd has finished executing before returning from __enter__
84
81
  """
85
- if not _CAFFEINATE_ENABLED:
82
+ if not self.SUPPORTED:
86
83
  raise NotImplementedError(f"This class is only available on macOS via: {CAFFEINATE}")
87
84
  if (
88
85
  isinstance(timeout, float)
@@ -129,7 +126,7 @@ class Caffeinate:
129
126
  pid = getpid()
130
127
  with self._instances_lock:
131
128
  if self._finalizing:
132
- raise PythonFinalizationError("No more new Caeffinate subprocesses are allowed")
129
+ raise PythonFinalizationError("No more new Caffeinate subprocesses are allowed")
133
130
  self._data = self._Data(pid, Popen(self._cmd)) # pylint: disable=consider-using-with
134
131
  self._instances.add(self)
135
132
  self._log.debug("Created Popen(%s), pid=%s", self._cmd, self._data.proc.pid)
@@ -158,7 +155,7 @@ class Caffeinate:
158
155
  self._stop(signal)
159
156
 
160
157
  @classmethod
161
- def decorate(
158
+ def decorate[**P, R](
162
159
  cls, cmd: list[Path | str | None] | None = None, **init_kwargs: object
163
160
  ) -> Callable[[Callable[P, R]], Callable[P, R]]:
164
161
  """A decorator to wrap a function with a Caffeinate instance
@@ -250,5 +247,5 @@ class Caffeinate:
250
247
 
251
248
 
252
249
  assert 0 not in Signals, "0 not expected in signal.Signals as it's a nop"
253
- if _CAFFEINATE_ENABLED:
250
+ if Caffeinate.SUPPORTED:
254
251
  atexit.register(Caffeinate._atexit) # pylint: disable=protected-access
@@ -0,0 +1,93 @@
1
+ from typing import Literal, overload
2
+ from collections.abc import Iterable
3
+ from shlex import quote
4
+
5
+ __all__ = ("prompt_for", "prompt_until", "yn_prompt")
6
+
7
+ @overload
8
+ def prompt_until(
9
+ msg: str,
10
+ until: str | Iterable[str],
11
+ *,
12
+ ignore_case: bool = True,
13
+ eof: Literal[False] = False,
14
+ ctrl_c: Literal[False] = False,
15
+ ) -> str: ...
16
+
17
+
18
+ @overload
19
+ def prompt_until(
20
+ msg: str,
21
+ until: str | Iterable[str],
22
+ *,
23
+ ignore_case: bool = True,
24
+ eof: bool = False,
25
+ ctrl_c: bool = False,
26
+ ) -> str | None: ...
27
+
28
+
29
+ def prompt_until(
30
+ msg: str,
31
+ until: str | Iterable[str],
32
+ *,
33
+ ignore_case: bool = True,
34
+ eof: bool = False,
35
+ ctrl_c: bool = False,
36
+ ) -> str | None:
37
+ """
38
+ Prompt the user with msg until they respone with a string in until, ignore case as needed
39
+ Whitespace is stripped
40
+ If ctrl_c and KeyboardInterrupt is caught, return None
41
+ If eof EOFError is caught, return None
42
+ Return the case-adjusted string the user entered
43
+ """
44
+ cased = lambda x: (x.casefold() if ignore_case else x)
45
+ until = frozenset(map(cased, (until,) if isinstance(until, str) else until))
46
+ try:
47
+ while (ret := cased(input(msg).strip())) not in until:
48
+ pass
49
+ return ret
50
+ except (EOFError, KeyboardInterrupt) as e:
51
+ if eof if isinstance(e, EOFError) else ctrl_c:
52
+ return None
53
+ raise
54
+
55
+
56
+ def prompt_for(
57
+ continue_str: str = "continue",
58
+ *,
59
+ ignore_case: bool = True,
60
+ eof: bool = False,
61
+ ctrl_c: bool = False,
62
+ ) -> bool:
63
+ """
64
+ Prompt the user to contine by entering continue_str, whitespace is stripped
65
+ If eof/ctrl_c, interpret EOFError/KeyboardInterrupt as commands to return False
66
+ """
67
+ ret = prompt_until(
68
+ f"Type {quote(continue_str)} ",
69
+ ignore_case=ignore_case,
70
+ until={continue_str},
71
+ eof=eof,
72
+ ctrl_c=ctrl_c,
73
+ )
74
+ return isinstance(ret, str)
75
+
76
+
77
+ def yn_prompt(
78
+ msg: str = "Yes or no?",
79
+ *,
80
+ eof: bool = False,
81
+ ctrl_c: bool = False,
82
+ yes_no: bool = False,
83
+ ) -> bool:
84
+ """
85
+ Prompt the user to select from [yn], or [yes/no] if [yes/no], whitespace is stripped
86
+ If eof/ctrl_c, interpret EOFError/KeyboardInterrupt as commands to return False
87
+ """
88
+ return prompt_until(
89
+ f"{msg} [{"yes/no" if yes_no else "yn"}] ",
90
+ until=("yes", "no") if yes_no else ("y", "n"),
91
+ eof=eof,
92
+ ctrl_c=ctrl_c,
93
+ ) in ("y", "yes")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zstdlib
3
- Version: 0.10.4
3
+ Version: 0.10.6
4
4
  Summary: A set of useful python utilities
5
5
  License: GPLv3
6
6
  Project-URL: Homepage, https://github.com/zwimer/zstdlib
@@ -6,9 +6,11 @@ tests/test_ansi.py
6
6
  tests/test_enum.py
7
7
  tests/test_exc_capture.py
8
8
  tests/test_frozen.py
9
+ tests/test_hybridmethod.py
9
10
  tests/test_io.py
10
11
  tests/test_lazy.py
11
12
  tests/test_not_set.py
13
+ tests/test_prompt.py
12
14
  tests/test_singleton.py
13
15
  tests/log/__init__.py
14
16
  tests/log/base.py
@@ -19,10 +21,12 @@ zstdlib/ansi.py
19
21
  zstdlib/enum.py
20
22
  zstdlib/exc_capture.py
21
23
  zstdlib/frozen.py
24
+ zstdlib/hybridmethod.py
22
25
  zstdlib/io.py
23
26
  zstdlib/lazy.py
24
27
  zstdlib/macos.py
25
28
  zstdlib/not_set.py
29
+ zstdlib/prompt.py
26
30
  zstdlib/py.typed
27
31
  zstdlib/signal_cm.py
28
32
  zstdlib/singleton.py
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
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