devkitx 1.0.0__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.
@@ -0,0 +1,262 @@
1
+ """System and process utilities for DevKitX.
2
+
3
+ This module provides utilities for system information, process execution,
4
+ and cross-platform system operations.
5
+ """
6
+
7
+ import asyncio
8
+ import os
9
+ import platform
10
+ import shutil
11
+ import socket
12
+ import subprocess
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ __all__ = [
17
+ "run_command",
18
+ "run_command_async",
19
+ "get_system_info",
20
+ "get_python_info",
21
+ "find_executable",
22
+ "get_env_vars",
23
+ "is_admin",
24
+ "get_free_port",
25
+ ]
26
+
27
+
28
+ def run_command(
29
+ cmd: list[str], timeout: float | None = None, cwd: str | Path | None = None
30
+ ) -> subprocess.CompletedProcess[str]:
31
+ """Run a command with timeout and error handling.
32
+
33
+ Args:
34
+ cmd: Command and arguments as list
35
+ timeout: Optional timeout in seconds
36
+ cwd: Optional working directory
37
+
38
+ Returns:
39
+ CompletedProcess result with stdout and stderr as strings
40
+
41
+ Raises:
42
+ subprocess.TimeoutExpired: If command times out
43
+ subprocess.CalledProcessError: If command returns non-zero exit code
44
+ FileNotFoundError: If command executable is not found
45
+ """
46
+ if not cmd:
47
+ raise ValueError("Command list cannot be empty")
48
+
49
+ # Convert Path to string if needed
50
+ if cwd is not None:
51
+ cwd = str(cwd)
52
+
53
+ try:
54
+ result = subprocess.run(
55
+ cmd, capture_output=True, text=True, timeout=timeout, cwd=cwd, check=True
56
+ )
57
+ return result
58
+ except subprocess.TimeoutExpired as e:
59
+ # Re-raise with more context
60
+ raise subprocess.TimeoutExpired(
61
+ cmd=e.cmd, timeout=e.timeout, output=e.output, stderr=e.stderr
62
+ ) from e
63
+ except subprocess.CalledProcessError as e:
64
+ # Re-raise with more context
65
+ raise subprocess.CalledProcessError(
66
+ returncode=e.returncode, cmd=e.cmd, output=e.output, stderr=e.stderr
67
+ ) from e
68
+ except FileNotFoundError as e:
69
+ # Provide more helpful error message
70
+ raise FileNotFoundError(f"Command '{cmd[0]}' not found in PATH") from e
71
+
72
+
73
+ async def run_command_async(
74
+ cmd: list[str], timeout: float | None = None
75
+ ) -> subprocess.CompletedProcess[str]:
76
+ """Run a command asynchronously with timeout.
77
+
78
+ Args:
79
+ cmd: Command and arguments as list
80
+ timeout: Optional timeout in seconds
81
+
82
+ Returns:
83
+ CompletedProcess result with stdout and stderr as strings
84
+
85
+ Raises:
86
+ asyncio.TimeoutError: If command times out
87
+ subprocess.CalledProcessError: If command returns non-zero exit code
88
+ FileNotFoundError: If command executable is not found
89
+ """
90
+ if not cmd:
91
+ raise ValueError("Command list cannot be empty")
92
+
93
+ try:
94
+ # Create subprocess
95
+ process = await asyncio.create_subprocess_exec(
96
+ *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
97
+ )
98
+
99
+ # Wait for completion with timeout
100
+ stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)
101
+
102
+ # Decode output
103
+ stdout_str = stdout.decode("utf-8") if stdout else ""
104
+ stderr_str = stderr.decode("utf-8") if stderr else ""
105
+
106
+ # Create CompletedProcess-like result
107
+ result = subprocess.CompletedProcess(
108
+ args=cmd, returncode=process.returncode or 0, stdout=stdout_str, stderr=stderr_str
109
+ )
110
+
111
+ # Check return code
112
+ if result.returncode != 0:
113
+ raise subprocess.CalledProcessError(
114
+ returncode=result.returncode, cmd=cmd, output=stdout_str, stderr=stderr_str
115
+ )
116
+
117
+ return result
118
+
119
+ except asyncio.TimeoutError as e:
120
+ # Kill the process if it's still running
121
+ if process and process.returncode is None:
122
+ process.kill()
123
+ await process.wait()
124
+ raise asyncio.TimeoutError(
125
+ f"Command '{' '.join(cmd)}' timed out after {timeout} seconds"
126
+ ) from e
127
+ except FileNotFoundError as e:
128
+ raise FileNotFoundError(f"Command '{cmd[0]}' not found in PATH") from e
129
+
130
+
131
+ def get_system_info() -> dict[str, str]:
132
+ """Get system information.
133
+
134
+ Returns:
135
+ Dictionary containing system information including OS name, version,
136
+ architecture, hostname, username, and CPU count
137
+ """
138
+ try:
139
+ import getpass
140
+
141
+ username = getpass.getuser()
142
+ except Exception:
143
+ username = os.environ.get("USER", os.environ.get("USERNAME", "unknown"))
144
+
145
+ try:
146
+ hostname = platform.node()
147
+ except Exception:
148
+ hostname = "unknown"
149
+
150
+ try:
151
+ cpu_count = os.cpu_count() or 0
152
+ except Exception:
153
+ cpu_count = 0
154
+
155
+ return {
156
+ "os_name": platform.system(),
157
+ "os_version": platform.release(),
158
+ "platform": platform.platform(),
159
+ "architecture": platform.machine(),
160
+ "processor": platform.processor() or "unknown",
161
+ "hostname": hostname,
162
+ "username": username,
163
+ "cpu_count": str(cpu_count),
164
+ }
165
+
166
+
167
+ def get_python_info() -> dict[str, str]:
168
+ """Get Python runtime information.
169
+
170
+ Returns:
171
+ Dictionary containing Python version, implementation, executable path,
172
+ and other runtime details
173
+ """
174
+ return {
175
+ "version": sys.version,
176
+ "version_info": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
177
+ "implementation": platform.python_implementation(),
178
+ "compiler": platform.python_compiler(),
179
+ "executable": sys.executable,
180
+ "prefix": sys.prefix,
181
+ "path": str(Path(sys.executable).parent),
182
+ "build": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
183
+ }
184
+
185
+
186
+ def find_executable(name: str) -> str | None:
187
+ """Find executable in system PATH.
188
+
189
+ Args:
190
+ name: Name of executable to find
191
+
192
+ Returns:
193
+ Path to executable or None if not found
194
+ """
195
+ if not name:
196
+ return None
197
+
198
+ # Use shutil.which which handles cross-platform executable finding
199
+ return shutil.which(name)
200
+
201
+
202
+ def get_env_vars(prefix: str = "") -> dict[str, str]:
203
+ """Get environment variables with optional prefix filter.
204
+
205
+ Args:
206
+ prefix: Optional prefix to filter variables
207
+
208
+ Returns:
209
+ Dictionary of environment variables matching the prefix
210
+ """
211
+ if not prefix:
212
+ return dict(os.environ)
213
+
214
+ return {key: value for key, value in os.environ.items() if key.startswith(prefix)}
215
+
216
+
217
+ def is_admin() -> bool:
218
+ """Check if running with administrator/root privileges.
219
+
220
+ Returns:
221
+ True if running as admin/root, False otherwise
222
+ """
223
+ try:
224
+ if platform.system() == "Windows":
225
+ import ctypes
226
+
227
+ return ctypes.windll.shell32.IsUserAnAdmin() != 0
228
+ else:
229
+ # Unix-like systems (Linux, macOS)
230
+ return os.geteuid() == 0
231
+ except Exception:
232
+ # If we can't determine, assume not admin for safety
233
+ return False
234
+
235
+
236
+ def get_free_port(start: int = 8000) -> int:
237
+ """Find a free port starting from the given port number.
238
+
239
+ Args:
240
+ start: Starting port number to check
241
+
242
+ Returns:
243
+ Available port number
244
+
245
+ Raises:
246
+ OSError: If no free port is found in reasonable range
247
+ """
248
+ if start < 1 or start > 65535:
249
+ raise ValueError("Port must be between 1 and 65535")
250
+
251
+ # Try ports starting from the given number
252
+ for port in range(start, 65536):
253
+ try:
254
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
255
+ sock.bind(("localhost", port))
256
+ return port
257
+ except OSError:
258
+ # Port is in use, try next one
259
+ continue
260
+
261
+ # If we get here, no free port was found
262
+ raise OSError(f"No free port found starting from {start}")
@@ -0,0 +1,433 @@
1
+ """Date and time utilities for DevKitX.
2
+
3
+ This module provides utilities for date parsing, formatting, timezone handling,
4
+ business day calculations, and scheduling.
5
+ """
6
+
7
+ import time
8
+ from datetime import datetime, timedelta
9
+ from typing import Any
10
+
11
+ __all__ = [
12
+ "parse_date",
13
+ "format_duration",
14
+ "get_timezone_offset",
15
+ "is_business_day",
16
+ "next_business_day",
17
+ "cron_next_run",
18
+ "Timer",
19
+ ]
20
+
21
+
22
+ def parse_date(date_str: str, formats: list[str] | None = None) -> datetime:
23
+ """Parse date string using multiple format attempts.
24
+
25
+ Args:
26
+ date_str: Date string to parse
27
+ formats: Optional list of date formats to try
28
+
29
+ Returns:
30
+ Parsed datetime object
31
+
32
+ Raises:
33
+ ValueError: If date string cannot be parsed with any format
34
+
35
+ Examples:
36
+ >>> parse_date("2024-01-15")
37
+ datetime.datetime(2024, 1, 15, 0, 0)
38
+ >>> parse_date("15/01/2024", ["%d/%m/%Y"])
39
+ datetime.datetime(2024, 1, 15, 0, 0)
40
+ """
41
+ if formats is None:
42
+ # Common date formats to try
43
+ formats = [
44
+ "%Y-%m-%d", # 2024-01-15
45
+ "%Y-%m-%d %H:%M:%S", # 2024-01-15 14:30:00
46
+ "%Y-%m-%d %H:%M", # 2024-01-15 14:30
47
+ "%Y/%m/%d", # 2024/01/15
48
+ "%Y/%m/%d %H:%M:%S", # 2024/01/15 14:30:00
49
+ "%Y/%m/%d %H:%M", # 2024/01/15 14:30
50
+ "%d-%m-%Y", # 15-01-2024
51
+ "%d-%m-%Y %H:%M:%S", # 15-01-2024 14:30:00
52
+ "%d-%m-%Y %H:%M", # 15-01-2024 14:30
53
+ "%d/%m/%Y", # 15/01/2024
54
+ "%d/%m/%Y %H:%M:%S", # 15/01/2024 14:30:00
55
+ "%d/%m/%Y %H:%M", # 15/01/2024 14:30
56
+ "%m-%d-%Y", # 01-15-2024
57
+ "%m-%d-%Y %H:%M:%S", # 01-15-2024 14:30:00
58
+ "%m-%d-%Y %H:%M", # 01-15-2024 14:30
59
+ "%m/%d/%Y", # 01/15/2024
60
+ "%m/%d/%Y %H:%M:%S", # 01/15/2024 14:30:00
61
+ "%m/%d/%Y %H:%M", # 01/15/2024 14:30
62
+ "%Y%m%d", # 20240115
63
+ "%Y%m%d%H%M%S", # 20240115143000
64
+ "%Y%m%d%H%M", # 202401151430
65
+ "%B %d, %Y", # January 15, 2024
66
+ "%b %d, %Y", # Jan 15, 2024
67
+ "%d %B %Y", # 15 January 2024
68
+ "%d %b %Y", # 15 Jan 2024
69
+ "%Y-%m-%dT%H:%M:%S", # ISO format without timezone
70
+ "%Y-%m-%dT%H:%M:%SZ", # ISO format with Z
71
+ "%Y-%m-%dT%H:%M:%S.%f", # ISO format with microseconds
72
+ "%Y-%m-%dT%H:%M:%S.%fZ", # ISO format with microseconds and Z
73
+ ]
74
+
75
+ # Try each format until one works
76
+ for fmt in formats:
77
+ try:
78
+ return datetime.strptime(date_str.strip(), fmt)
79
+ except ValueError:
80
+ continue
81
+
82
+ # If no format worked, raise an error
83
+ raise ValueError(f"Unable to parse date string '{date_str}' with any of the provided formats")
84
+
85
+
86
+ def format_duration(seconds: float) -> str:
87
+ """Format duration in seconds to human-readable string.
88
+
89
+ Args:
90
+ seconds: Duration in seconds
91
+
92
+ Returns:
93
+ Human-readable duration string
94
+
95
+ Examples:
96
+ >>> format_duration(30)
97
+ '30.0s'
98
+ >>> format_duration(90)
99
+ '1m 30.0s'
100
+ >>> format_duration(3661)
101
+ '1h 1m 1.0s'
102
+ >>> format_duration(90061)
103
+ '1d 1h 1m 1.0s'
104
+ """
105
+ if seconds < 0:
106
+ return f"-{format_duration(-seconds)}"
107
+
108
+ if seconds == 0:
109
+ return "0.0s"
110
+
111
+ # Time units in seconds
112
+ units = [
113
+ ("d", 86400), # days
114
+ ("h", 3600), # hours
115
+ ("m", 60), # minutes
116
+ ("s", 1), # seconds
117
+ ]
118
+
119
+ parts = []
120
+ remaining = seconds
121
+ started = False # Track if we've started adding units
122
+
123
+ for unit_name, unit_seconds in units:
124
+ if remaining >= unit_seconds or started:
125
+ if unit_name == "s":
126
+ # For seconds, show decimal places
127
+ parts.append(f"{remaining:.1f}{unit_name}")
128
+ break
129
+ else:
130
+ # For other units, use integer division
131
+ count = int(remaining // unit_seconds)
132
+ parts.append(f"{count}{unit_name}")
133
+ remaining = remaining % unit_seconds
134
+ if count > 0:
135
+ started = True
136
+
137
+ # If we only have fractional seconds left and no other parts
138
+ if not parts and remaining > 0:
139
+ parts.append(f"{remaining:.1f}s")
140
+
141
+ return " ".join(parts)
142
+
143
+
144
+ def get_timezone_offset(tz_name: str) -> timedelta:
145
+ """Get timezone offset from UTC.
146
+
147
+ Args:
148
+ tz_name: Timezone name (e.g., 'US/Eastern', 'Europe/London', 'UTC')
149
+
150
+ Returns:
151
+ Timezone offset as timedelta
152
+
153
+ Raises:
154
+ ValueError: If timezone name is not recognized
155
+
156
+ Examples:
157
+ >>> get_timezone_offset("UTC")
158
+ datetime.timedelta(0)
159
+ >>> # Note: Actual offsets depend on current date due to DST
160
+ """
161
+ try:
162
+ from zoneinfo import ZoneInfo
163
+ except ImportError:
164
+ # Fallback for Python < 3.9 or systems without zoneinfo
165
+ try:
166
+ import pytz
167
+
168
+ tz = pytz.timezone(tz_name)
169
+ # Get current offset (this will vary with DST)
170
+ now = datetime.now(tz)
171
+ return now.utcoffset() or timedelta(0)
172
+ except ImportError:
173
+ # Basic fallback for common timezones
174
+ common_offsets = {
175
+ "UTC": timedelta(0),
176
+ "GMT": timedelta(0),
177
+ "EST": timedelta(hours=-5),
178
+ "CST": timedelta(hours=-6),
179
+ "MST": timedelta(hours=-7),
180
+ "PST": timedelta(hours=-8),
181
+ "EDT": timedelta(hours=-4),
182
+ "CDT": timedelta(hours=-5),
183
+ "MDT": timedelta(hours=-6),
184
+ "PDT": timedelta(hours=-7),
185
+ }
186
+ if tz_name in common_offsets:
187
+ return common_offsets[tz_name]
188
+ raise ValueError(f"Timezone '{tz_name}' not recognized and zoneinfo/pytz not available")
189
+
190
+ try:
191
+ tz = ZoneInfo(tz_name)
192
+ # Get current offset (this will vary with DST)
193
+ now = datetime.now(tz)
194
+ return now.utcoffset() or timedelta(0)
195
+ except Exception as e:
196
+ raise ValueError(f"Invalid timezone name '{tz_name}': {e}")
197
+
198
+
199
+ def is_business_day(date: datetime) -> bool:
200
+ """Check if date is a business day (Monday-Friday).
201
+
202
+ Args:
203
+ date: Date to check
204
+
205
+ Returns:
206
+ True if business day, False otherwise
207
+
208
+ Examples:
209
+ >>> # Monday is a business day
210
+ >>> is_business_day(datetime(2024, 1, 15)) # Monday
211
+ True
212
+ >>> # Saturday is not a business day
213
+ >>> is_business_day(datetime(2024, 1, 13)) # Saturday
214
+ False
215
+ >>> # Sunday is not a business day
216
+ >>> is_business_day(datetime(2024, 1, 14)) # Sunday
217
+ False
218
+ """
219
+ # Monday is 0, Sunday is 6
220
+ return date.weekday() < 5
221
+
222
+
223
+ def next_business_day(date: datetime) -> datetime:
224
+ """Get next business day from given date.
225
+
226
+ Args:
227
+ date: Starting date
228
+
229
+ Returns:
230
+ Next business day (preserves time component)
231
+
232
+ Examples:
233
+ >>> # From Friday, next business day is Monday
234
+ >>> next_business_day(datetime(2024, 1, 12, 14, 30)) # Friday
235
+ datetime.datetime(2024, 1, 15, 14, 30)
236
+ >>> # From Wednesday, next business day is Thursday
237
+ >>> next_business_day(datetime(2024, 1, 10, 9, 0)) # Wednesday
238
+ datetime.datetime(2024, 1, 11, 9, 0)
239
+ """
240
+ next_date = date + timedelta(days=1)
241
+
242
+ # Keep adding days until we find a business day
243
+ while not is_business_day(next_date):
244
+ next_date += timedelta(days=1)
245
+
246
+ return next_date
247
+
248
+
249
+ def cron_next_run(cron_expr: str, from_time: datetime | None = None) -> datetime:
250
+ """Calculate next run time for cron expression.
251
+
252
+ This is a simplified cron parser that supports basic cron expressions.
253
+ Format: "minute hour day_of_month month day_of_week"
254
+
255
+ Args:
256
+ cron_expr: Cron expression (e.g., "0 9 * * 1-5" for 9 AM on weekdays)
257
+ from_time: Starting time, defaults to now
258
+
259
+ Returns:
260
+ Next scheduled run time
261
+
262
+ Raises:
263
+ ValueError: If cron expression is invalid
264
+
265
+ Examples:
266
+ >>> # Every day at 9 AM
267
+ >>> cron_next_run("0 9 * * *", datetime(2024, 1, 15, 8, 0))
268
+ datetime.datetime(2024, 1, 15, 9, 0)
269
+ >>> # Every weekday at 9 AM
270
+ >>> cron_next_run("0 9 * * 1-5", datetime(2024, 1, 13, 10, 0)) # Saturday
271
+ datetime.datetime(2024, 1, 15, 9, 0) # Next Monday
272
+ """
273
+ if from_time is None:
274
+ from_time = datetime.now()
275
+
276
+ # Parse cron expression
277
+ parts = cron_expr.strip().split()
278
+ if len(parts) != 5:
279
+ raise ValueError(
280
+ "Cron expression must have 5 parts: minute hour day_of_month month day_of_week"
281
+ )
282
+
283
+ minute_expr, hour_expr, day_expr, month_expr, dow_expr = parts
284
+
285
+ def parse_field(expr: str, min_val: int, max_val: int) -> set[int]:
286
+ """Parse a single cron field."""
287
+ if expr == "*":
288
+ return set(range(min_val, max_val + 1))
289
+
290
+ values = set()
291
+ for part in expr.split(","):
292
+ if "-" in part:
293
+ start, end = part.split("-", 1)
294
+ values.update(range(int(start), int(end) + 1))
295
+ elif "/" in part:
296
+ range_part, step = part.split("/", 1)
297
+ if range_part == "*":
298
+ base_values = set(range(min_val, max_val + 1))
299
+ else:
300
+ base_values = parse_field(range_part, min_val, max_val)
301
+ values.update(v for v in base_values if (v - min_val) % int(step) == 0)
302
+ else:
303
+ values.add(int(part))
304
+
305
+ return {v for v in values if min_val <= v <= max_val}
306
+
307
+ try:
308
+ minutes = parse_field(minute_expr, 0, 59)
309
+ hours = parse_field(hour_expr, 0, 23)
310
+ days = parse_field(day_expr, 1, 31)
311
+ months = parse_field(month_expr, 1, 12)
312
+ # Parse day of week (cron: Sunday=0, Monday=1, ..., Saturday=6)
313
+ # Python weekday(): Monday=0, Tuesday=1, ..., Sunday=6
314
+ dow_raw = parse_field(dow_expr, 0, 7)
315
+ # Convert cron weekday to Python weekday
316
+ days_of_week = set()
317
+ for d in dow_raw:
318
+ if d == 0 or d == 7: # Sunday in cron
319
+ days_of_week.add(6) # Sunday in Python
320
+ else: # Monday-Saturday in cron (1-6)
321
+ days_of_week.add(d - 1) # Monday-Saturday in Python (0-5)
322
+
323
+ # Validate that we have valid values
324
+ if not minutes or not hours or not days or not months or not days_of_week:
325
+ raise ValueError("Invalid field values")
326
+
327
+ except (ValueError, IndexError) as e:
328
+ raise ValueError(f"Invalid cron expression '{cron_expr}': {e}")
329
+
330
+ # Start from the next minute
331
+ current = from_time.replace(second=0, microsecond=0) + timedelta(minutes=1)
332
+
333
+ # Search for next valid time (limit to avoid infinite loops)
334
+ for _ in range(366 * 24 * 60): # Max 1 year of minutes
335
+ if (
336
+ current.minute in minutes
337
+ and current.hour in hours
338
+ and current.day in days
339
+ and current.month in months
340
+ and current.weekday() in days_of_week
341
+ ):
342
+ return current
343
+
344
+ current += timedelta(minutes=1)
345
+
346
+ raise ValueError(f"Could not find next run time for cron expression '{cron_expr}'")
347
+
348
+
349
+ class Timer:
350
+ """Simple timer for measuring elapsed time.
351
+
352
+ Examples:
353
+ >>> timer = Timer()
354
+ >>> timer.start()
355
+ >>> # ... do some work ...
356
+ >>> elapsed = timer.stop()
357
+ >>> print(f"Operation took {elapsed:.2f} seconds")
358
+
359
+ >>> # Or use as context manager
360
+ >>> with Timer() as timer:
361
+ ... # ... do some work ...
362
+ ... pass
363
+ >>> print(f"Operation took {timer.elapsed():.2f} seconds")
364
+ """
365
+
366
+ def __init__(self) -> None:
367
+ """Initialize timer."""
368
+ self._start_time: float | None = None
369
+ self._end_time: float | None = None
370
+
371
+ def start(self) -> None:
372
+ """Start the timer.
373
+
374
+ Raises:
375
+ RuntimeError: If timer is already running
376
+ """
377
+ if self._start_time is not None and self._end_time is None:
378
+ raise RuntimeError("Timer is already running")
379
+
380
+ self._start_time = time.perf_counter()
381
+ self._end_time = None
382
+
383
+ def stop(self) -> float:
384
+ """Stop the timer and return elapsed time.
385
+
386
+ Returns:
387
+ Elapsed time in seconds
388
+
389
+ Raises:
390
+ RuntimeError: If timer was not started
391
+ """
392
+ if self._start_time is None:
393
+ raise RuntimeError("Timer was not started")
394
+
395
+ if self._end_time is None:
396
+ self._end_time = time.perf_counter()
397
+
398
+ return self._end_time - self._start_time
399
+
400
+ def elapsed(self) -> float:
401
+ """Get elapsed time without stopping timer.
402
+
403
+ Returns:
404
+ Elapsed time in seconds
405
+
406
+ Raises:
407
+ RuntimeError: If timer was not started
408
+ """
409
+ if self._start_time is None:
410
+ raise RuntimeError("Timer was not started")
411
+
412
+ end_time = self._end_time if self._end_time is not None else time.perf_counter()
413
+ return end_time - self._start_time
414
+
415
+ def reset(self) -> None:
416
+ """Reset the timer to initial state."""
417
+ self._start_time = None
418
+ self._end_time = None
419
+
420
+ def restart(self) -> None:
421
+ """Restart the timer (reset and start)."""
422
+ self.reset()
423
+ self.start()
424
+
425
+ def __enter__(self) -> "Timer":
426
+ """Context manager entry."""
427
+ self.start()
428
+ return self
429
+
430
+ def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
431
+ """Context manager exit."""
432
+ if self._end_time is None:
433
+ self.stop()