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

@ -806,8 +806,8 @@ class Retry(contextlib.ContextDecorator):
"""
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
specified number of times with an exponentially increasing delay between retries.
Can be used as a decorator to retry a function on exceptions, up to a specified number of times with an
exponentially increasing delay between retries.
Examples:
Example usage as a decorator:
@ -815,11 +815,6 @@ class Retry(contextlib.ContextDecorator):
>>> def test_func():
>>> # Replace with function logic that may raise exceptions
>>> 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):
@ -846,20 +841,6 @@ class Retry(contextlib.ContextDecorator):
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):
"""

View file

@ -33,7 +33,6 @@ from ultralytics.utils import (
ROOT,
TORCHVISION_VERSION,
USER_CONFIG_DIR,
Retry,
SimpleNamespace,
ThreadingLocked,
TryExcept,
@ -390,8 +389,7 @@ def check_requirements(requirements=ROOT.parent / "requirements.txt", exclude=()
try:
t = time.time()
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
LOGGER.info(
f"{prefix} AutoUpdate success ✅ {dt:.1f}s, installed {n} package{'s' * (n > 1)}: {pkgs}\n"