Skip to content

Commit bc7682e

Browse files
committed
fix: Remove unused variables and convert dict comprehensions
- Remove unused 'model' variable assignments in test files - Remove unused 'original_threshold' variable assignment - Convert dict comprehensions to dict() calls as required by newer Ruff rules - Follow C416 rule: {x: y for x, y in zip(...)} -> dict(zip(...)) - Fix trailing whitespace issues These fixes address specific Ruff linting errors from GitHub CI
1 parent 4a6e495 commit bc7682e

9 files changed

Lines changed: 41 additions & 44 deletions

src/automation/deployment_trigger.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,15 @@
99
import logging
1010
import subprocess
1111
import sys
12-
from typing import Any, Optional
12+
from typing import Any
1313

1414
logger = logging.getLogger(__name__)
1515

1616

1717
class DeploymentTrigger:
1818
"""Simple deployment trigger using subprocess calls."""
1919

20-
def __init__(self, config_path: Optional[str] = None):
20+
def __init__(self, config_path: str | None = None):
2121
"""Initialize the deployment trigger.
2222
2323
Args:
@@ -28,7 +28,7 @@ def __init__(self, config_path: Optional[str] = None):
2828
def trigger_deployment(
2929
self,
3030
deployment_name: str,
31-
parameters: Optional[dict[str, Any]] = None,
31+
parameters: dict[str, Any] | None = None,
3232
wait_for_completion: bool = False,
3333
timeout_seconds: int = 300,
3434
) -> bool:
@@ -156,11 +156,11 @@ async def trigger_deployment():
156156
def trigger_retraining(
157157
self,
158158
deployment_name: str = "simulation-triggered-retraining",
159-
week: Optional[int] = None,
160-
performance_drop: Optional[float] = None,
161-
baseline_score: Optional[float] = None,
162-
current_score: Optional[float] = None,
163-
training_data_path: Optional[str] = None,
159+
week: int | None = None,
160+
performance_drop: float | None = None,
161+
baseline_score: float | None = None,
162+
current_score: float | None = None,
163+
training_data_path: str | None = None,
164164
wait_for_completion: bool = True,
165165
timeout_seconds: int = 300,
166166
) -> bool:

src/automation/prefect_client.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ async def trigger_deployment_run(
9696
deployments = await client.read_deployments()
9797
available = [d.name for d in deployments]
9898
logger.info(f"Available deployments: {available}")
99-
except:
99+
except Exception:
100100
pass
101101
raise ValueError(f"Deployment '{deployment_name}' not found")
102102

src/automation/retraining_flow.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
import sys
1111
from datetime import datetime, timedelta
1212
from pathlib import Path
13-
from typing import Any, Optional
13+
from typing import Any
1414

1515
import pandas as pd
1616
from prefect import flow, task
@@ -79,7 +79,7 @@ def backup_current_model(
7979
@task(name="prepare-retraining-data")
8080
def prepare_retraining_data(
8181
original_data_path: str,
82-
new_data_path: Optional[str] = None,
82+
new_data_path: str | None = None,
8383
data_window_days: int = 365,
8484
) -> tuple[pd.DataFrame, pd.DataFrame, dict]:
8585
"""Prepare data for retraining with new observations."""
@@ -159,7 +159,7 @@ def train_new_model(
159159
train_data: pd.DataFrame,
160160
val_data: pd.DataFrame,
161161
model_type: str = "random_forest",
162-
hyperparameters: Optional[dict] = None,
162+
hyperparameters: dict | None = None,
163163
) -> tuple[str, dict]:
164164
"""Train a new model with the prepared data."""
165165
logger = get_run_logger()
@@ -324,7 +324,7 @@ def deploy_new_model(
324324
model_file_path: str,
325325
model_path: str,
326326
validation_results: dict,
327-
deployment_metadata: Optional[dict] = None,
327+
deployment_metadata: dict | None = None,
328328
) -> dict:
329329
"""Deploy the new model if validation passed."""
330330
logger = get_run_logger()
@@ -467,12 +467,12 @@ def automated_retraining_flow(
467467
triggers: list[str],
468468
model_path: str = "models/model.pkl",
469469
training_data_path: str = "data/real_data/premier_league_matches.parquet",
470-
new_data_path: Optional[str] = None,
470+
new_data_path: str | None = None,
471471
backup_dir: str = "models/backups",
472472
model_type: str = "random_forest",
473473
min_accuracy_threshold: float = 0.45,
474474
improvement_threshold: float = 0.01,
475-
hyperparameters: Optional[dict] = None,
475+
hyperparameters: dict | None = None,
476476
) -> dict[str, Any]:
477477
"""
478478
Main automated retraining flow.

src/automation/retraining_scheduler.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
from dataclasses import dataclass, field
1313
from datetime import datetime
1414
from pathlib import Path
15-
from typing import Any, Optional
15+
from typing import Any
1616

1717
import yaml
1818

@@ -84,8 +84,8 @@ class AutomatedRetrainingScheduler:
8484

8585
def __init__(
8686
self,
87-
config: Optional[RetrainingConfig] = None,
88-
config_path: Optional[str] = None,
87+
config: RetrainingConfig | None = None,
88+
config_path: str | None = None,
8989
):
9090
"""
9191
Initialize the automated retraining scheduler.
@@ -123,9 +123,9 @@ def __init__(
123123

124124
# State management
125125
self.is_running = False
126-
self.scheduler_thread: Optional[threading.Thread] = None
127-
self.last_check_time: Optional[datetime] = None
128-
self.last_retraining_time: Optional[datetime] = None
126+
self.scheduler_thread: threading.Thread | None = None
127+
self.last_check_time: datetime | None = None
128+
self.last_retraining_time: datetime | None = None
129129
self.retraining_in_progress = False
130130
self.retraining_lock = threading.Lock()
131131

@@ -437,7 +437,7 @@ def _get_recent_performance_metrics(self) -> list[dict]:
437437
logger.error(f"Error getting performance metrics: {str(e)}")
438438
return []
439439

440-
def _get_baseline_accuracy(self) -> Optional[float]:
440+
def _get_baseline_accuracy(self) -> float | None:
441441
"""Get baseline accuracy for comparison."""
442442
# This could be from initial model evaluation, target accuracy, etc.
443443
return self.retraining_orchestrator.baseline_performance or 0.55 # 55% baseline
@@ -520,7 +520,7 @@ def make_serializable(obj: Any) -> Any:
520520
for k, v in obj.__dict__.items()
521521
if not k.startswith("_")
522522
}
523-
elif isinstance(obj, (list, tuple)):
523+
elif isinstance(obj, list | tuple):
524524
return [make_serializable(item) for item in obj]
525525
elif isinstance(obj, dict):
526526
return {k: make_serializable(v) for k, v in obj.items()}

src/config/__init__.py

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,22 +7,21 @@
77

88
import os
99
from pathlib import Path
10-
from typing import Optional
1110

1211

13-
def load_environment(env_file: Optional[str] = None) -> bool:
12+
def load_environment(env_file: str | None = None) -> bool:
1413
"""
1514
Load environment variables from .env file.
16-
15+
1716
Args:
1817
env_file: Path to .env file. If None, looks for .env in project root.
19-
18+
2019
Returns:
2120
bool: True if .env file was loaded successfully, False otherwise.
2221
"""
2322
try:
2423
from dotenv import load_dotenv
25-
24+
2625
if env_file is None:
2726
# Find project root (look for pyproject.toml)
2827
current_path = Path(__file__).parent
@@ -36,37 +35,37 @@ def load_environment(env_file: Optional[str] = None) -> bool:
3635
env_path = Path(".env")
3736
else:
3837
env_path = Path(env_file)
39-
38+
4039
if env_path.exists():
4140
load_dotenv(env_path)
4241
return True
4342
else:
4443
return False
45-
44+
4645
except ImportError:
4746
return False
4847

4948

50-
def get_env_var(key: str, default: Optional[str] = None, required: bool = False) -> str:
49+
def get_env_var(key: str, default: str | None = None, required: bool = False) -> str:
5150
"""
5251
Get environment variable with proper error handling.
53-
52+
5453
Args:
5554
key: Environment variable name
5655
default: Default value if not found
5756
required: Whether the variable is required
58-
57+
5958
Returns:
6059
str: Environment variable value
61-
60+
6261
Raises:
6362
ValueError: If required variable is not found
6463
"""
6564
value = os.environ.get(key, default)
66-
65+
6766
if required and value is None:
6867
raise ValueError(f"Required environment variable '{key}' not found")
69-
68+
7069
return value or ""
7170

7271

src/simulation/retraining_orchestrator.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import os
1010
from datetime import datetime
1111
from pathlib import Path
12-
from typing import Any, Optional
12+
from typing import Any
1313

1414
import joblib
1515
import pandas as pd
@@ -69,7 +69,7 @@ def __init__(
6969
self.output_dir.mkdir(parents=True, exist_ok=True)
7070

7171
# Initialize deployment trigger if using Prefect
72-
self.deployment_trigger: Optional[Any] = None
72+
self.deployment_trigger: Any | None = None
7373
if self.use_prefect:
7474
try:
7575
# Set Prefect API URL to connect to the main server

tests/e2e/test_enhanced_model.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ def main():
6565
print("\n" + "=" * 60)
6666
print("🧠 Training improved model...")
6767
trainer = ModelTrainer(model_type="random_forest")
68-
model = trainer.train(train_data, val_data)
68+
trainer.train(train_data, val_data)
6969

7070
# Evaluate model
7171
print("\n" + "=" * 60)
@@ -116,7 +116,7 @@ def main():
116116
print(f"📈 Probabilities: {probabilities[0]}")
117117

118118
# Create probability mapping
119-
prob_mapping = {cls: prob for cls, prob in zip(class_order, probabilities[0], strict=False)}
119+
prob_mapping = dict(zip(class_order, probabilities[0], strict=False))
120120
print("\n📊 Model probability breakdown:")
121121
for cls, prob in prob_mapping.items():
122122
result_name = {"H": "Home Win", "D": "Draw", "A": "Away Win"}[cls]

tests/integration/test_automated_retraining_integration.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -224,8 +224,6 @@ def test_configuration_persistence_and_updates(self, temp_workspace):
224224
# Load scheduler with file-based config
225225
scheduler = AutomatedRetrainingScheduler(config_path=str(config_path))
226226

227-
original_threshold = scheduler.config.performance_threshold
228-
229227
# Update configuration at runtime
230228
new_config = RetrainingConfig(
231229
performance_threshold=0.08, # Different from original

tests/integration/test_enhanced_model_integration.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ def main():
6262
print("\n" + "=" * 60)
6363
print("🧠 Training improved model...")
6464
trainer = ModelTrainer(model_type="random_forest")
65-
model = trainer.train(train_data, val_data)
65+
trainer.train(train_data, val_data)
6666

6767
# Evaluate model
6868
print("\n" + "=" * 60)
@@ -113,7 +113,7 @@ def main():
113113
print(f"📈 Probabilities: {probabilities[0]}")
114114

115115
# Create probability mapping
116-
prob_mapping = {cls: prob for cls, prob in zip(class_order, probabilities[0], strict=False)}
116+
prob_mapping = dict(zip(class_order, probabilities[0], strict=False))
117117
print("\n📊 Model probability breakdown:")
118118
for cls, prob in prob_mapping.items():
119119
result_name = {"H": "Home Win", "D": "Draw", "A": "Away Win"}[cls]

0 commit comments

Comments
 (0)