mirror of
https://github.com/kuhyx/testsAndMisc-archive.git
synced 2026-11-26 21:27:21 +01:00
fix: resolve PERF203 try-except in loop violations
- Extract try-except bodies into helper functions: - download_cats: _download_single_image() - randomize_numbers: _parse_single_number() - lichess_bot/main: _apply_move_to_board(), _process_event_stream(), _run_event_loop_iteration() - Use else block for return statements after try (TRY300) - Remove PERF203 from per-file ignores in pyproject.toml
This commit is contained in:
parent
22333931cc
commit
aeb5b679a0
@ -15,18 +15,13 @@ logging.basicConfig(level=logging.INFO)
|
|||||||
MAX_REQUESTS = 90
|
MAX_REQUESTS = 90
|
||||||
REQUEST_TIMEOUT = 30 # seconds
|
REQUEST_TIMEOUT = 30 # seconds
|
||||||
|
|
||||||
requests_send = 0
|
|
||||||
while requests_send < MAX_REQUESTS:
|
|
||||||
res = requests.get(
|
|
||||||
"https://api.thecatapi.com/v1/images/search?limit=100&api_key=",
|
|
||||||
timeout=REQUEST_TIMEOUT,
|
|
||||||
)
|
|
||||||
requests_send += 1
|
|
||||||
response = json.loads(res.text)
|
|
||||||
urls = [cat.get("url") for cat in response]
|
|
||||||
|
|
||||||
Path("./CATS2").mkdir(parents=True, exist_ok=True)
|
def _download_single_image(url: str) -> None:
|
||||||
for url in urls:
|
"""Download and save a single image from URL.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
url: The URL of the image to download.
|
||||||
|
"""
|
||||||
try:
|
try:
|
||||||
# Get the image content
|
# Get the image content
|
||||||
response = requests.get(url, timeout=REQUEST_TIMEOUT)
|
response = requests.get(url, timeout=REQUEST_TIMEOUT)
|
||||||
@ -44,3 +39,18 @@ while requests_send < MAX_REQUESTS:
|
|||||||
|
|
||||||
except requests.exceptions.RequestException:
|
except requests.exceptions.RequestException:
|
||||||
logging.exception(f"Failed to download {url}")
|
logging.exception(f"Failed to download {url}")
|
||||||
|
|
||||||
|
|
||||||
|
requests_send = 0
|
||||||
|
while requests_send < MAX_REQUESTS:
|
||||||
|
res = requests.get(
|
||||||
|
"https://api.thecatapi.com/v1/images/search?limit=100&api_key=",
|
||||||
|
timeout=REQUEST_TIMEOUT,
|
||||||
|
)
|
||||||
|
requests_send += 1
|
||||||
|
response = json.loads(res.text)
|
||||||
|
urls = [cat.get("url") for cat in response]
|
||||||
|
|
||||||
|
Path("./CATS2").mkdir(parents=True, exist_ok=True)
|
||||||
|
for url in urls:
|
||||||
|
_download_single_image(url)
|
||||||
|
|||||||
@ -18,6 +18,20 @@ from python_pkg.lichess_bot.lichess_api import LichessAPI
|
|||||||
from python_pkg.lichess_bot.utils import backoff_sleep, get_and_increment_version
|
from python_pkg.lichess_bot.utils import backoff_sleep, get_and_increment_version
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_move_to_board(board: chess.Board, move: str, game_id: str) -> None:
|
||||||
|
"""Apply a single move to the board, logging errors.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
board: The chess board to apply the move to.
|
||||||
|
move: The UCI move string.
|
||||||
|
game_id: The game ID for logging purposes.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
board.push_uci(move)
|
||||||
|
except Exception:
|
||||||
|
logging.debug(f"Game {game_id}: could not apply move {move}")
|
||||||
|
|
||||||
|
|
||||||
def run_bot(log_level: str = "INFO", *, decline_correspondence: bool = False) -> None:
|
def run_bot(log_level: str = "INFO", *, decline_correspondence: bool = False) -> None:
|
||||||
"""Start the bot and listen for incoming events."""
|
"""Start the bot and listen for incoming events."""
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
@ -136,10 +150,7 @@ def run_bot(log_level: str = "INFO", *, decline_correspondence: bool = False) ->
|
|||||||
# Rebuild board from moves
|
# Rebuild board from moves
|
||||||
board = chess.Board()
|
board = chess.Board()
|
||||||
for m in moves_list:
|
for m in moves_list:
|
||||||
try:
|
_apply_move_to_board(board, m, game_id)
|
||||||
board.push_uci(m)
|
|
||||||
except Exception:
|
|
||||||
logging.debug(f"Game {game_id}: could not apply move {m}")
|
|
||||||
|
|
||||||
if color is None:
|
if color is None:
|
||||||
logging.info(
|
logging.info(
|
||||||
@ -394,11 +405,11 @@ def run_bot(log_level: str = "INFO", *, decline_correspondence: bool = False) ->
|
|||||||
logging.debug(f"Game {game_id}: could not write PGN: {e}")
|
logging.debug(f"Game {game_id}: could not write PGN: {e}")
|
||||||
logging.info(f"Ending game thread for {game_id}")
|
logging.info(f"Ending game thread for {game_id}")
|
||||||
|
|
||||||
# Main event stream: challenge and game start events
|
def _process_event_stream() -> None:
|
||||||
logging.info("Connecting to Lichess event stream. Waiting for challenges...")
|
"""Process events from the Lichess event stream.
|
||||||
backoff = 0
|
|
||||||
while True:
|
Handles challenges and game start/finish events.
|
||||||
try:
|
"""
|
||||||
for event in api.stream_events():
|
for event in api.stream_events():
|
||||||
if event.get("type") == "challenge":
|
if event.get("type") == "challenge":
|
||||||
challenge = event["challenge"]
|
challenge = event["challenge"]
|
||||||
@ -423,10 +434,7 @@ def run_bot(log_level: str = "INFO", *, decline_correspondence: bool = False) ->
|
|||||||
elif event.get("type") == "gameStart":
|
elif event.get("type") == "gameStart":
|
||||||
game_id = event["game"]["id"]
|
game_id = event["game"]["id"]
|
||||||
# Spin up a game thread
|
# Spin up a game thread
|
||||||
if (
|
if game_id not in game_threads or not game_threads[game_id].is_alive():
|
||||||
game_id not in game_threads
|
|
||||||
or not game_threads[game_id].is_alive()
|
|
||||||
):
|
|
||||||
t = threading.Thread(
|
t = threading.Thread(
|
||||||
target=handle_game, args=(game_id,), name=f"game-{game_id}"
|
target=handle_game, args=(game_id,), name=f"game-{game_id}"
|
||||||
)
|
)
|
||||||
@ -439,11 +447,27 @@ def run_bot(log_level: str = "INFO", *, decline_correspondence: bool = False) ->
|
|||||||
logging.info(f"Game finished event: {game_id}")
|
logging.info(f"Game finished event: {game_id}")
|
||||||
else:
|
else:
|
||||||
logging.debug(f"Unhandled event: {json.dumps(event)}")
|
logging.debug(f"Unhandled event: {json.dumps(event)}")
|
||||||
# If stream ends normally, reset backoff
|
|
||||||
backoff = 0
|
def _run_event_loop_iteration() -> int:
|
||||||
|
"""Run one iteration of the event loop with error handling.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
New backoff value (0 on success, increased on error).
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
_process_event_stream()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logging.warning(f"Event stream error: {e}")
|
logging.warning(f"Event stream error: {e}")
|
||||||
backoff = backoff_sleep(backoff)
|
return backoff_sleep(backoff)
|
||||||
|
else:
|
||||||
|
# If stream ends normally, reset backoff
|
||||||
|
return 0
|
||||||
|
|
||||||
|
# Main event stream: challenge and game start events
|
||||||
|
logging.info("Connecting to Lichess event stream. Waiting for challenges...")
|
||||||
|
backoff = 0
|
||||||
|
while True:
|
||||||
|
backoff = _run_event_loop_iteration()
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
|
|||||||
@ -43,14 +43,30 @@ def parse_input(input_string: str) -> tuple[list[float], list[int]]:
|
|||||||
numbers: list[float] = []
|
numbers: list[float] = []
|
||||||
decimal_counts: list[int] = []
|
decimal_counts: list[int] = []
|
||||||
for num in number_strings:
|
for num in number_strings:
|
||||||
|
parsed = _parse_single_number(num)
|
||||||
|
if parsed is not None:
|
||||||
|
float_num, digits_count = parsed
|
||||||
|
numbers.append(float_num)
|
||||||
|
decimal_counts.append(digits_count)
|
||||||
|
return numbers, decimal_counts
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_single_number(num: str) -> tuple[float, int] | None:
|
||||||
|
"""Parse a single number string into float and decimal count.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
num: The number string to parse.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Tuple of (float value, decimal count) or None if invalid.
|
||||||
|
"""
|
||||||
try:
|
try:
|
||||||
float_num = float(num)
|
float_num = float(num)
|
||||||
digits_count = len(num.split(".")[-1]) if "." in num else 0
|
digits_count = len(num.split(".")[-1]) if "." in num else 0
|
||||||
numbers.append(float_num)
|
|
||||||
decimal_counts.append(digits_count)
|
|
||||||
except ValueError:
|
except ValueError:
|
||||||
continue
|
return None
|
||||||
return numbers, decimal_counts
|
else:
|
||||||
|
return float_num, digits_count
|
||||||
|
|
||||||
|
|
||||||
MIN_ARGS = 2
|
MIN_ARGS = 2
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user