Skip to content

Commit

Permalink
Merge pull request #70 from qua-platform/update_linting_rules
Browse files Browse the repository at this point in the history
Refactor: update linting rules
  • Loading branch information
nulinspiratie authored Oct 25, 2024
2 parents 7c5f371 + 8e43f1d commit 36f6891
Show file tree
Hide file tree
Showing 29 changed files with 263 additions and 257 deletions.
46 changes: 26 additions & 20 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 13 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ setuptools = "^75.1.0" # it's required for qm ->


[tool.poetry.group.dev.dependencies]
ruff = "^0.4.8"
ruff = "^0.7.0"
mypy = "^1.10.0"
poethepoet = "^0.27.0"

Expand All @@ -33,7 +33,18 @@ target-version = "py39"
exclude = ["calibrations"]

[tool.ruff.lint]
extend-select = ["I"]
select = [
"E", # pycodestyle
"F", # Pyflakes
"UP", # pyupgrade
"B", # flake8-bugbear
"SIM", # flake8-simplify
"I", # isort
]

[tool.ruff.lint.pycodestyle]
max-line-length = 80
max-doc-length = 80

[tool.mypy]
python_version = "3.9"
Expand Down
5 changes: 3 additions & 2 deletions qualibrate/models/execution_history.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from collections.abc import Sequence
from datetime import datetime
from typing import Dict, Optional, Sequence
from typing import Optional

from pydantic import BaseModel, ConfigDict, Field, computed_field

Expand All @@ -23,7 +24,7 @@ class ExecutionHistoryItem(BaseModel):
run_end: datetime
parameters: NodeParameters
error: Optional[RunError] = None
outcomes: Dict[TargetType, Outcome] = Field(default_factory=dict)
outcomes: dict[TargetType, Outcome] = Field(default_factory=dict)

@computed_field
def run_duration(self) -> float:
Expand Down
11 changes: 6 additions & 5 deletions qualibrate/models/run_summary/base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from collections.abc import Mapping, Sequence
from datetime import datetime
from typing import Any, Dict, List, Mapping, Optional, Sequence
from typing import Any, Optional

from pydantic import BaseModel, Field, computed_field, field_serializer

Expand All @@ -17,13 +18,13 @@ class BaseRunSummary(BaseModel):
created_at: datetime
completed_at: datetime
parameters: Optional[RunnableParameters] = None
outcomes: Dict[TargetType, Outcome]
outcomes: dict[TargetType, Outcome]
error: Optional[RunError] = None

initial_targets: Sequence[TargetType] = Field(default_factory=list)
successful_targets: List[TargetType] = Field(default_factory=list)
failed_targets: List[TargetType] = Field(default_factory=list)
dropped_targets: Optional[List[TargetType]] = None
successful_targets: list[TargetType] = Field(default_factory=list)
failed_targets: list[TargetType] = Field(default_factory=list)
dropped_targets: Optional[list[TargetType]] = None
state_updates: Mapping[str, Any] = Field(default_factory=dict)

@computed_field
Expand Down
3 changes: 2 additions & 1 deletion qualibrate/orchestration/basic_orchestrator.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import traceback
from collections.abc import Sequence
from datetime import datetime
from queue import Queue
from typing import Any, Generic, Optional, Sequence
from typing import Any, Generic, Optional

import networkx as nx

Expand Down
17 changes: 8 additions & 9 deletions qualibrate/orchestration/qualibration_orchestrator.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from abc import ABC, abstractmethod
from typing import Any, Dict, Generic, List, Mapping, Optional, Sequence
from collections.abc import Mapping, Sequence
from typing import Any, Generic, Optional

from pydantic import create_model

Expand All @@ -16,9 +17,6 @@
__all__ = ["QualibrationOrchestrator"]


# NodeType = TypeVar("NodeType", bound=QualibrationNode[NodeParameters])


class QualibrationOrchestrator(ABC, Generic[NodeTypeVar]):
"""
Abstract base class for orchestrating the execution of nodes in a
Expand All @@ -29,7 +27,8 @@ class QualibrationOrchestrator(ABC, Generic[NodeTypeVar]):
clean up resources, and serialize the orchestrator's current state.
Args:
**parameters (Any): Keyword arguments for initializing the orchestrator parameters.
**parameters: Keyword arguments for initializing the orchestrator
parameters.
"""

def __init__(self, **parameters: Any):
Expand All @@ -43,11 +42,11 @@ def __init__(self, **parameters: Any):
},
)
self._parameters = self.parameters_class()
self.initial_targets: Optional[List[Any]] = None
self.targets: Optional[List[Any]] = None
self._execution_history: List[ExecutionHistoryItem] = []
self.initial_targets: Optional[list[Any]] = None
self.targets: Optional[list[Any]] = None
self._execution_history: list[ExecutionHistoryItem] = []
self._active_node: Optional[NodeTypeVar] = None
self.final_outcomes: Dict[Any, Outcome] = {}
self.final_outcomes: dict[Any, Outcome] = {}

@property
def active_node(self) -> Optional[NodeTypeVar]:
Expand Down
18 changes: 9 additions & 9 deletions qualibrate/parameters.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import sys
from collections.abc import Mapping, Sequence
from typing import (
Any,
ClassVar,
List,
Mapping,
Optional,
Sequence,
cast,
)

from pydantic import BaseModel, Field, model_validator

from qualibrate.utils.logger_m import logger
from qualibrate.utils.naming import get_full_class_path
from qualibrate.utils.parameters import recursive_properties_solver
Expand All @@ -20,7 +20,6 @@
else:
from typing_extensions import Self

from pydantic import BaseModel, Field, model_validator

__all__ = [
"ExecutionParameters",
Expand Down Expand Up @@ -75,21 +74,22 @@ def targets_exists_if_specified(self) -> Self:
return self

@property
def targets(self) -> Optional[List[TargetType]]:
def targets(self) -> Optional[list[TargetType]]:
if (
self.targets_name is None
or self.targets_name not in self.model_fields
):
return None
return cast(List[TargetType], getattr(self, self.targets_name))
return cast(list[TargetType], getattr(self, self.targets_name))

@targets.setter
def targets(self, new_targets: Sequence[TargetType]) -> None:
if self.targets_name is None:
return
if self.targets_name not in self.model_fields:
raise ValueError(
f"Targets name ({self.targets_name}) specified but field does not exist"
f"Targets name ({self.targets_name}) specified but field does "
"not exist"
)
if not isinstance(new_targets, Sequence):
raise ValueError(f"Targets must be an iterable of {TargetType}")
Expand Down Expand Up @@ -134,7 +134,7 @@ class NodesParameters(RunnableParameters):
class GraphParameters(RunnableParameters, TargetParameter):
targets_name: ClassVar[Optional[str]] = "qubits"

qubits: List[TargetType] = Field(default_factory=list)
qubits: list[TargetType] = Field(default_factory=list)

@classmethod
def serialize(
Expand All @@ -161,7 +161,7 @@ def serialize(cls, **kwargs: Any) -> Mapping[str, Any]:
for k, v in serialized.items()
if k not in ("parameters", "nodes")
}
exclude_targets = kwargs.get("exclude_targets", None)
exclude_targets = kwargs.get("exclude_targets")
exclude_parameters_targets = (
exclude_targets if exclude_targets is not None else False
)
Expand Down
32 changes: 15 additions & 17 deletions qualibrate/q_runnnable.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
from abc import ABC, abstractmethod
from collections.abc import Mapping
from contextvars import ContextVar
from copy import copy
from pathlib import Path
from typing import (
Any,
Dict,
Generic,
Mapping,
Optional,
Tuple,
Type,
TypeVar,
cast,
)
Expand Down Expand Up @@ -45,10 +42,10 @@ class QRunnable(ABC, Generic[CreateParametersType, RunParametersType]):
Abstract base class representing a runnable task.
Args:
name (str): The name of the runnable.
parameters (CreateParametersType): Parameters to initialize the runnable.
description (Optional[str]): Description of the runnable.
modes (Optional[RunModes]): Optional run modes for the runnable.
name: The name of the runnable.
parameters: Parameters to initialize the runnable.
description: Description of the runnable.
modes: Optional run modes for the runnable.
"""

modes = RunModes()
Expand All @@ -74,7 +71,7 @@ def __init__(

self._state_updates: dict[str, Any] = {}

self.outcomes: Dict[TargetType, Outcome] = {}
self.outcomes: dict[TargetType, Outcome] = {}
self.run_summary: Optional[BaseRunSummary] = None

def cleanup(self) -> None:
Expand All @@ -88,15 +85,15 @@ def cleanup(self) -> None:
@staticmethod
def build_parameters_class_from_instance(
parameters: CreateParametersType,
) -> Type[CreateParametersType]:
) -> type[CreateParametersType]:
"""
Builds a parameter class from a given instance.
Args:
parameters (CreateParametersType): The parameters instance.
Returns:
Type[CreateParametersType]: A new parameter class type.
A new parameter class type.
"""
fields = {
name: copy(field) for name, field in parameters.model_fields.items()
Expand All @@ -113,15 +110,16 @@ def build_parameters_class_from_instance(
)
if hasattr(parameters, "targets_name"):
model.targets_name = parameters.targets_name
return cast(Type[CreateParametersType], model)
return cast(type[CreateParametersType], model)

@classmethod
def get_run_modes(cls, modes: Optional[RunModes] = None) -> RunModes:
"""
Determines the run modes for the QRunnable.
If modes are provided, they are returned.
If no modes are provided, the context run modes are returned.
If no context run modes are provided, the default run modes are returned.
If no context run modes are provided, the default run modes are
returned.
Args:
modes (Optional[RunModes]): Run modes, if provided.
Expand Down Expand Up @@ -184,22 +182,22 @@ def stop(self, **kwargs: Any) -> bool:
@abstractmethod
def scan_folder_for_instances(
cls, path: Path
) -> Dict[str, "QRunnable[CreateParametersType, RunParametersType]"]:
) -> dict[str, "QRunnable[CreateParametersType, RunParametersType]"]:
"""
Scans a folder for runnable instances.
Args:
path (Path): The folder path to scan.
Returns:
Dict[str, QRunnable]: A dictionary of runnable instances.
dict[str, QRunnable]: A dictionary of runnable instances.
"""
pass

@abstractmethod
def run(
self, **passed_parameters: Any
) -> Tuple[
) -> tuple[
"QRunnable[CreateParametersType, RunParametersType]",
BaseRunSummary,
]:
Expand All @@ -210,7 +208,7 @@ def run(
**passed_parameters (Any): Parameters to run the runnable.
Returns:
Tuple[QRunnable, BaseRunSummary]: The executed runnable and summary.
tuple[QRunnable, BaseRunSummary]: The executed runnable and summary.
"""
pass

Expand Down
Loading

0 comments on commit 36f6891

Please sign in to comment.