nano-dev-utils 0.5.6__py3-none-any.whl → 0.5.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of nano-dev-utils might be problematic. Click here for more details.

@@ -0,0 +1,18 @@
1
+ """nano-dev-utils - A collection of small Python utilities for developers.
2
+ Copyright (c) 2025 Yaron Dayan
3
+ """
4
+
5
+ from .dynamic_importer import Importer
6
+ from .timers import Timer
7
+ from .release_ports import PortsRelease, PROXY_SERVER, INSPECTOR_CLIENT
8
+ from importlib.metadata import version
9
+
10
+ __version__ = version('nano-dev-utils')
11
+
12
+ __all__ = [
13
+ 'Importer',
14
+ 'Timer',
15
+ 'PortsRelease',
16
+ 'PROXY_SERVER',
17
+ 'INSPECTOR_CLIENT',
18
+ ]
@@ -0,0 +1,27 @@
1
+ from types import ModuleType
2
+ from typing import Any
3
+
4
+ import importlib
5
+
6
+
7
+ class Importer:
8
+ def __init__(self):
9
+ self.imported_modules = {}
10
+
11
+ def import_mod_from_lib(self, library: str, module_name: str) -> ModuleType | Any:
12
+ """Lazily imports and caches a specific submodule from a given library.
13
+ :param library: The name of the library.
14
+ :param module_name: The name of the module to import.
15
+ :return: The imported module.
16
+ """
17
+ if module_name in self.imported_modules:
18
+ return self.imported_modules[module_name]
19
+
20
+ lib_mod = f'{library}.{module_name}'
21
+
22
+ try:
23
+ module = importlib.import_module(lib_mod)
24
+ self.imported_modules[module_name] = module
25
+ return module
26
+ except ModuleNotFoundError as e:
27
+ raise ImportError(f'Could not import {lib_mod}') from e
@@ -0,0 +1,155 @@
1
+ import platform
2
+ import subprocess
3
+ import logging
4
+
5
+ lgr = logging.getLogger(__name__)
6
+ """Module-level logger. Configure using logging.basicConfig() in your application."""
7
+
8
+ PROXY_SERVER = 6277
9
+ INSPECTOR_CLIENT = 6274
10
+
11
+
12
+ class PortsRelease:
13
+ def __init__(self, default_ports: list[int] | None = None):
14
+ self.default_ports: list[int] = (
15
+ default_ports
16
+ if default_ports is not None
17
+ else [PROXY_SERVER, INSPECTOR_CLIENT]
18
+ )
19
+
20
+ @staticmethod
21
+ def _log_process_found(port: int, pid: int) -> str:
22
+ return f'Process ID (PID) found for port {port}: {pid}.'
23
+
24
+ @staticmethod
25
+ def _log_process_terminated(pid: int, port: int) -> str:
26
+ return f'Process {pid} (on port {port}) terminated successfully.'
27
+
28
+ @staticmethod
29
+ def _log_no_process(port: int) -> str:
30
+ return f'No process found listening on port {port}.'
31
+
32
+ @staticmethod
33
+ def _log_invalid_port(port: int) -> str:
34
+ return f'Invalid port number: {port}. Skipping.'
35
+
36
+ @staticmethod
37
+ def _log_terminate_failed(
38
+ pid: int, port: int | None = None, error: str | None = None
39
+ ) -> str:
40
+ base_msg = f'Failed to terminate process {pid}'
41
+ if port:
42
+ base_msg += f' (on port {port})'
43
+ if error:
44
+ base_msg += f'. Error: {error}'
45
+ return base_msg
46
+
47
+ @staticmethod
48
+ def _log_line_parse_failed(line: str) -> str:
49
+ return f'Could not parse PID from line: {line}'
50
+
51
+ @staticmethod
52
+ def _log_unexpected_error(e: Exception) -> str:
53
+ return f'An unexpected error occurred: {e}'
54
+
55
+ @staticmethod
56
+ def _log_cmd_error(error: bytes) -> str:
57
+ return f'Error running command: {error.decode()}'
58
+
59
+ @staticmethod
60
+ def _log_unsupported_os() -> str:
61
+ return f'Unsupported OS: {platform.system()}'
62
+
63
+ def get_pid_by_port(self, port: int) -> int | None:
64
+ """Gets the process ID (PID) listening on the specified port."""
65
+ system = platform.system()
66
+ try:
67
+ cmd: str = {
68
+ 'Windows': f'netstat -ano | findstr :{port}',
69
+ 'Linux': f'ss -lntp | grep :{port}',
70
+ 'Darwin': f'lsof -i :{port}',
71
+ }.get(system, '')
72
+ if not cmd:
73
+ lgr.error(self._log_unsupported_os())
74
+ return None
75
+
76
+ process = subprocess.Popen(
77
+ cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
78
+ )
79
+ output, error = process.communicate()
80
+ if error:
81
+ lgr.error(self._log_cmd_error(error))
82
+ return None
83
+
84
+ lines: list[str] = output.decode().splitlines()
85
+ for line in lines:
86
+ if str(port) in line:
87
+ parts: list[str] = line.split()
88
+ if system == 'Windows' and len(parts) > 4:
89
+ try:
90
+ return int(parts[4])
91
+ except ValueError:
92
+ lgr.error(self._log_line_parse_failed(line))
93
+ return None
94
+ elif system == 'Linux':
95
+ for part in parts:
96
+ if 'pid=' in part:
97
+ try:
98
+ return int(part.split('=')[1])
99
+ except ValueError:
100
+ lgr.error(self._log_line_parse_failed(line))
101
+ return None
102
+ elif system == 'Darwin' and len(parts) > 1:
103
+ try:
104
+ return int(parts[1])
105
+ except ValueError:
106
+ lgr.error(self._log_line_parse_failed(line))
107
+ return None
108
+ return None
109
+ except Exception as e:
110
+ lgr.error(self._log_unexpected_error(e))
111
+ return None
112
+
113
+ def kill_process(self, pid: int) -> bool:
114
+ """Kills the process with the specified PID."""
115
+ try:
116
+ cmd: str = {
117
+ 'Windows': f'taskkill /F /PID {pid}',
118
+ 'Linux': f'kill -9 {pid}',
119
+ 'Darwin': f'kill -9 {pid}',
120
+ }.get(platform.system(), '') # fallback to empty string
121
+ if not cmd:
122
+ lgr.error(self._log_unsupported_os())
123
+ return False
124
+ process = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE)
125
+ _, error = process.communicate()
126
+ if process.returncode:
127
+ error_msg = error.decode()
128
+ lgr.error(self._log_terminate_failed(pid=pid, error=error_msg))
129
+ return False
130
+ return True
131
+ except Exception as e:
132
+ lgr.error(self._log_unexpected_error(e))
133
+ return False
134
+
135
+ def release_all(self, ports: list[int] | None = None) -> None:
136
+ try:
137
+ ports_to_release: list[int] = self.default_ports if ports is None else ports
138
+
139
+ for port in ports_to_release:
140
+ if not isinstance(port, int):
141
+ lgr.error(self._log_invalid_port(port))
142
+ continue
143
+
144
+ pid: int | None = self.get_pid_by_port(port)
145
+ if pid is None:
146
+ lgr.info(self._log_no_process(port))
147
+ continue
148
+
149
+ lgr.info(self._log_process_found(port, pid))
150
+ if self.kill_process(pid):
151
+ lgr.info(self._log_process_terminated(pid, port))
152
+ else:
153
+ lgr.error(self._log_terminate_failed(pid=pid, port=port))
154
+ except Exception as e:
155
+ lgr.error(self._log_unexpected_error(e))
@@ -0,0 +1,49 @@
1
+ from functools import wraps
2
+ import time
3
+ from typing import Callable, ParamSpec, TypeVar
4
+
5
+ P = ParamSpec('P')
6
+ R = TypeVar('R')
7
+
8
+
9
+ class Timer:
10
+ def __init__(self, precision=4, verbose=False):
11
+ self.precision = precision
12
+ self.verbose = verbose
13
+ self.units = [(1e9, 's'), (1e6, 'ms'), (1e3, 'μs'), (1.0, 'ns')]
14
+
15
+ def timeit(
16
+ self, iterations: int = 1
17
+ ) -> Callable[[Callable[P, R]], Callable[P, R | None]]:
18
+ def decorator(func: Callable[P, R]) -> Callable[P, R | None]:
19
+ """Decorator that times function execution with automatic unit scaling and averaging."""
20
+
21
+ @wraps(func)
22
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None:
23
+ total_elapsed = 0
24
+ result = None
25
+
26
+ for _ in range(iterations):
27
+ start = time.perf_counter_ns()
28
+ result = func(*args, **kwargs)
29
+ total_elapsed += time.perf_counter_ns() - start
30
+
31
+ avg_elapsed = total_elapsed / iterations
32
+ value = avg_elapsed
33
+ unit = 'ns'
34
+
35
+ for divisor, unit in self.units:
36
+ if avg_elapsed >= divisor or unit == 'ns':
37
+ value = avg_elapsed / divisor
38
+ break
39
+
40
+ extra_info = f'{args} {kwargs} ' if self.verbose else ''
41
+ iter_info = f' (avg over {iterations} runs)' if iterations > 1 else ''
42
+ print(
43
+ f'{func.__name__} {extra_info}took {value:.{self.precision}f} [{unit}]{iter_info}'
44
+ )
45
+ return result
46
+
47
+ return wrapper
48
+
49
+ return decorator
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: nano_dev_utils
3
- Version: 0.5.6
3
+ Version: 0.5.8
4
4
  Summary: A collection of small Python utilities for developers.
5
5
  Project-URL: Homepage, https://github.com/yaronday/nano_utils
6
6
  Project-URL: Issues, https://github.com/yaronday/nano_utils/issues
@@ -34,10 +34,12 @@ This module provides a `Timer` class for measuring the execution time of code bl
34
34
  * `verbose`: Optionally displays the function's positional arguments (args) and keyword arguments (kwargs).
35
35
  Defaults to `False`.
36
36
 
37
- * **`timeit(self, func: Callable[P, R]) -> Callable[P, R]`**:
37
+ * **`timeit(
38
+ self, iterations: int = 1
39
+ ) -> Callable[[Callable[P, R]], Callable[P, R | None]]`**:
38
40
  Decorator that times function execution with automatic unit scaling.
39
41
  * When the decorated function is called, this decorator records the start and end times,
40
- calculates the total execution time, prints the function name and execution
42
+ calculates the average execution time, prints the function name and execution
41
43
  time (optionally including arguments), and returns the result of the original function.
42
44
 
43
45
  #### Example Usage:
@@ -49,7 +51,7 @@ from nano_dev_utils.timers import Timer
49
51
  timer = Timer(precision=6, verbose=True)
50
52
 
51
53
 
52
- @timer.timeit
54
+ @timer.timeit()
53
55
  def my_function(a, b=10):
54
56
  """A sample function."""
55
57
  time.sleep(0.1)
@@ -0,0 +1,8 @@
1
+ nano_dev_utils/__init__.py,sha256=imiI367TPj5s4IFmi-VrKJLbdkIxdIPISNscthoaS9U,454
2
+ nano_dev_utils/dynamic_importer.py,sha256=cm2VwDYSGwhGZNO3uMX-O0LaKtEFtzkPm7BrZW4igG4,911
3
+ nano_dev_utils/release_ports.py,sha256=sgmoPax9Hpcse1rHbBSnDJWTkvV6aWpZ5hQFxBKhGR8,5886
4
+ nano_dev_utils/timers.py,sha256=IiCltOHRkYqfX_IzHQ2Xty4ptITBiaOldFO1HhQ6r_A,1748
5
+ nano_dev_utils-0.5.8.dist-info/METADATA,sha256=KA_vxHbiStc8At1rFrWu2Rt8G_eJzyrRLeb3tYQWfUs,5550
6
+ nano_dev_utils-0.5.8.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
7
+ nano_dev_utils-0.5.8.dist-info/licenses/LICENSE,sha256=Muenl7Bw_LdtHZtlOMAP7Kt97gDCq8WWp2605eDWhHU,1089
8
+ nano_dev_utils-0.5.8.dist-info/RECORD,,
@@ -1,5 +0,0 @@
1
- LICENSE,sha256=Muenl7Bw_LdtHZtlOMAP7Kt97gDCq8WWp2605eDWhHU,1089
2
- nano_dev_utils-0.5.6.dist-info/METADATA,sha256=X5nF5ZkwJ4UmQMISX2ZDiDEP8OQV7yMjCeACZuAKy3k,5498
3
- nano_dev_utils-0.5.6.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
4
- nano_dev_utils-0.5.6.dist-info/licenses/LICENSE,sha256=Muenl7Bw_LdtHZtlOMAP7Kt97gDCq8WWp2605eDWhHU,1089
5
- nano_dev_utils-0.5.6.dist-info/RECORD,,
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 Yaron Dayan
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.