Abandon with Retry(): context manager (#13159)

Signed-off-by: Glenn Jocher <glenn.jocher@ultralytics.com>
This commit is contained in:
Glenn Jocher 2024-05-28 03:10:17 +02:00 committed by GitHub
parent 22de23ec8d
commit 25c9f77c8f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 4 additions and 27 deletions

View file

@ -15,7 +15,6 @@ from ultralytics.utils import (
LINUX, LINUX,
MACOS, MACOS,
WINDOWS, WINDOWS,
Retry,
checks, checks,
) )
from ultralytics.utils.torch_utils import TORCH_1_9, TORCH_1_13 from ultralytics.utils.torch_utils import TORCH_1_9, TORCH_1_13
@ -69,8 +68,7 @@ def test_export_openvino_matrix(task, dynamic, int8, half, batch):
file = Path(file) file = Path(file)
file = file.rename(file.with_stem(f"{file.stem}-{uuid.uuid4()}")) file = file.rename(file.with_stem(f"{file.stem}-{uuid.uuid4()}"))
YOLO(file)([SOURCE] * batch, imgsz=64 if dynamic else 32) # exported model inference YOLO(file)([SOURCE] * batch, imgsz=64 if dynamic else 32) # exported model inference
with Retry(times=3, delay=1): # retry in case of potential lingering multi-threaded file usage errors shutil.rmtree(file, ignore_errors=True) # retry in case of potential lingering multi-threaded file usage errors
shutil.rmtree(file)
@pytest.mark.slow @pytest.mark.slow

View file

@ -806,8 +806,8 @@ class Retry(contextlib.ContextDecorator):
""" """
Retry class for function execution with exponential backoff. Retry class for function execution with exponential backoff.
Can be used as a decorator or a context manager to retry a function or block of code on exceptions, up to a Can be used as a decorator to retry a function on exceptions, up to a specified number of times with an
specified number of times with an exponentially increasing delay between retries. exponentially increasing delay between retries.
Examples: Examples:
Example usage as a decorator: Example usage as a decorator:
@ -815,11 +815,6 @@ class Retry(contextlib.ContextDecorator):
>>> def test_func(): >>> def test_func():
>>> # Replace with function logic that may raise exceptions >>> # Replace with function logic that may raise exceptions
>>> return True >>> return True
Example usage as a context manager:
>>> with Retry(times=3, delay=2):
>>> # Replace with code block that may raise exceptions
>>> pass
""" """
def __init__(self, times=3, delay=2): def __init__(self, times=3, delay=2):
@ -846,20 +841,6 @@ class Retry(contextlib.ContextDecorator):
return wrapped_func return wrapped_func
def __enter__(self):
"""Enter the runtime context related to this object."""
self._attempts = 0
def __exit__(self, exc_type, exc_value, traceback):
"""Exit the runtime context related to this object with exponential backoff."""
if exc_type is not None:
self._attempts += 1
if self._attempts < self.times:
print(f"Retry {self._attempts}/{self.times} failed: {exc_value}")
time.sleep(self.delay * (2**self._attempts)) # exponential backoff delay
return True # Suppresses the exception and retries
return False # Re-raises the exception if retries are exhausted
def threaded(func): def threaded(func):
""" """

View file

@ -33,7 +33,6 @@ from ultralytics.utils import (
ROOT, ROOT,
TORCHVISION_VERSION, TORCHVISION_VERSION,
USER_CONFIG_DIR, USER_CONFIG_DIR,
Retry,
SimpleNamespace, SimpleNamespace,
ThreadingLocked, ThreadingLocked,
TryExcept, TryExcept,
@ -390,8 +389,7 @@ def check_requirements(requirements=ROOT.parent / "requirements.txt", exclude=()
try: try:
t = time.time() t = time.time()
assert ONLINE, "AutoUpdate skipped (offline)" assert ONLINE, "AutoUpdate skipped (offline)"
with Retry(times=2, delay=1): # run up to 2 times with 1-second retry delay LOGGER.info(subprocess.check_output(f"pip install --no-cache-dir {s} {cmds}", shell=True).decode())
LOGGER.info(subprocess.check_output(f"pip install --no-cache-dir {s} {cmds}", shell=True).decode())
dt = time.time() - t dt = time.time() - t
LOGGER.info( LOGGER.info(
f"{prefix} AutoUpdate success ✅ {dt:.1f}s, installed {n} package{'s' * (n > 1)}: {pkgs}\n" f"{prefix} AutoUpdate success ✅ {dt:.1f}s, installed {n} package{'s' * (n > 1)}: {pkgs}\n"