diff --git a/benchmarking/benchmarks/dataset.py b/benchmarking/benchmarks/dataset.py index 8175e19cba43..e005640986e2 100644 --- a/benchmarking/benchmarks/dataset.py +++ b/benchmarking/benchmarks/dataset.py @@ -50,8 +50,8 @@ class Adding5Params: timer = time.perf_counter def __init__(self): - self.parameters = list() - self.values = list() + self.parameters = [] + self.values = [] self.experiment = None self.runner = None self.datasaver = None @@ -116,8 +116,8 @@ def teardown(self, bench_param): shutil.rmtree(self.tmpdir) self.tmpdir = None - self.parameters = list() - self.values = list() + self.parameters = [] + self.values = [] def time_test(self, bench_param): """Adding data for 5 parameters""" diff --git a/docs/examples/DataSet/Accessing-data-in-DataSet.ipynb b/docs/examples/DataSet/Accessing-data-in-DataSet.ipynb index ead14498b532..6f53db227006 100644 --- a/docs/examples/DataSet/Accessing-data-in-DataSet.ipynb +++ b/docs/examples/DataSet/Accessing-data-in-DataSet.ipynb @@ -972,7 +972,7 @@ " print(f\"DataFrame for parameter {parameter_name}\")\n", " print(\"-----------------------------\")\n", " print(f\"{df.head()!r}\")\n", - " print(\"\")" + " print()" ] }, { diff --git a/docs/examples/DataSet/Offline Plotting Tutorial.ipynb b/docs/examples/DataSet/Offline Plotting Tutorial.ipynb index a784e4e05e62..6519f9cd2aa9 100644 --- a/docs/examples/DataSet/Offline Plotting Tutorial.ipynb +++ b/docs/examples/DataSet/Offline Plotting Tutorial.ipynb @@ -669,17 +669,11 @@ "\n", "\n", "def no_x(xv):\n", - " if xv > 0 and xv < 3:\n", - " return True\n", - " else:\n", - " return False\n", + " return bool(xv > 0 and xv < 3)\n", "\n", "\n", "def no_t(tv):\n", - " if tv > 0 and tv < 450:\n", - " return True\n", - " else:\n", - " return False\n", + " return bool(tv > 0 and tv < 450)\n", "\n", "\n", "with meas.run() as datasaver:\n", diff --git a/docs/examples/DataSet/Using_doNd_functions_in_comparison_to_Measurement_context_manager_for_performing_measurements.ipynb b/docs/examples/DataSet/Using_doNd_functions_in_comparison_to_Measurement_context_manager_for_performing_measurements.ipynb index 2825d51aef3e..662bb91d5ee7 100644 --- a/docs/examples/DataSet/Using_doNd_functions_in_comparison_to_Measurement_context_manager_for_performing_measurements.ipynb +++ b/docs/examples/DataSet/Using_doNd_functions_in_comparison_to_Measurement_context_manager_for_performing_measurements.ipynb @@ -1742,9 +1742,8 @@ } ], "source": [ - "with qcodes.logger.console_level(\"DEBUG\"):\n", - " with qcodes.logger.filter_instrument(dac):\n", - " dond(set_only_sweep, dmm.v1, dmm.v2)" + "with qcodes.logger.console_level(\"DEBUG\"), qcodes.logger.filter_instrument(dac):\n", + " dond(set_only_sweep, dmm.v1, dmm.v2)" ] }, { @@ -1802,9 +1801,8 @@ } ], "source": [ - "with qcodes.logger.console_level(\"DEBUG\"):\n", - " with qcodes.logger.filter_instrument(dac):\n", - " dond(set_and_get_sweep, dmm.v1, dmm.v2)" + "with qcodes.logger.console_level(\"DEBUG\"), qcodes.logger.filter_instrument(dac):\n", + " dond(set_and_get_sweep, dmm.v1, dmm.v2)" ] }, { diff --git a/docs/examples/basic_examples/Configuring_QCoDeS.ipynb b/docs/examples/basic_examples/Configuring_QCoDeS.ipynb index 7b2c87135024..0a02fb04a7c8 100644 --- a/docs/examples/basic_examples/Configuring_QCoDeS.ipynb +++ b/docs/examples/basic_examples/Configuring_QCoDeS.ipynb @@ -250,9 +250,7 @@ ], "source": [ "print(\n", - " \"\\n\".join(\n", - " [qc.config.home_file_name, qc.config.env_file_name, qc.config.cwd_file_name]\n", - " )\n", + " f\"{qc.config.home_file_name}\\n{qc.config.env_file_name}\\n{qc.config.cwd_file_name}\"\n", ")" ] }, diff --git a/docs/examples/driver_examples/QCodes example with Keithley S46.ipynb b/docs/examples/driver_examples/QCodes example with Keithley S46.ipynb index 66b7f4eeae58..dc3f6dc2dd9e 100644 --- a/docs/examples/driver_examples/QCodes example with Keithley S46.ipynb +++ b/docs/examples/driver_examples/QCodes example with Keithley S46.ipynb @@ -177,7 +177,7 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": null, "metadata": {}, "outputs": [ { @@ -191,7 +191,7 @@ "source": [ "try:\n", " s46.A2(\"close\")\n", - " raise (\"We should not be here\")\n", + " raise RuntimeError(\"We should not be here\")\n", "except KeithleyS46LockAcquisitionError as e:\n", " print(e)" ] @@ -216,7 +216,7 @@ }, { "cell_type": "code", - "execution_count": 14, + "execution_count": null, "metadata": {}, "outputs": [ { @@ -230,7 +230,7 @@ "source": [ "try:\n", " s46.A1(\"close\")\n", - " raise (\"We should not be here\")\n", + " raise RuntimeError(\"We should not be here\")\n", "except KeithleyS46LockAcquisitionError as e:\n", " print(e)" ] @@ -246,7 +246,7 @@ }, { "cell_type": "code", - "execution_count": 16, + "execution_count": null, "metadata": {}, "outputs": [ { @@ -260,7 +260,7 @@ "source": [ "try:\n", " s46.B2(\"close\")\n", - " raise (\"We should not be here\")\n", + " raise RuntimeError(\"We should not be here\")\n", "except KeithleyS46LockAcquisitionError as e:\n", " print(e)" ] diff --git a/docs/examples/logging/logfile_parsing.ipynb b/docs/examples/logging/logfile_parsing.ipynb index 052d217ef29b..60c6d817ea87 100644 --- a/docs/examples/logging/logfile_parsing.ipynb +++ b/docs/examples/logging/logfile_parsing.ipynb @@ -53,9 +53,8 @@ "source": [ "# put the 30MB into a zip file\n", "filepath = os.path.join(os.getcwd(), \"static\", \"pythonlog.zip\")\n", - "with ZipFile(filepath) as z:\n", - " with z.open(\"pythonlog.log\", \"r\") as f:\n", - " my_log = [line.decode() for line in f]" + "with ZipFile(filepath) as z, z.open(\"pythonlog.log\", \"r\") as f:\n", + " my_log = [line.decode() for line in f]" ] }, { diff --git a/docs/examples/logging/logging_example.ipynb b/docs/examples/logging/logging_example.ipynb index aa68a1972c33..819d5fb5a51e 100644 --- a/docs/examples/logging/logging_example.ipynb +++ b/docs/examples/logging/logging_example.ipynb @@ -292,9 +292,8 @@ ], "source": [ "driver.cartesian((0, 0, 0))\n", - "with logger.console_level(\"DEBUG\"):\n", - " with logger.filter_instrument(mag_x):\n", - " driver.cartesian((0, 0, 1))" + "with logger.console_level(\"DEBUG\"), logger.filter_instrument(mag_x):\n", + " driver.cartesian((0, 0, 1))" ] }, { @@ -330,9 +329,8 @@ ], "source": [ "driver.cartesian((0, 0, 0))\n", - "with logger.console_level(\"DEBUG\"):\n", - " with logger.filter_instrument((mag_x, mag_y)):\n", - " driver.cartesian((0, 0, 1))" + "with logger.console_level(\"DEBUG\"), logger.filter_instrument((mag_x, mag_y)):\n", + " driver.cartesian((0, 0, 1))" ] }, { @@ -360,7 +358,7 @@ "metadata": {}, "outputs": [], "source": [ - "with logger.console_level(logging.WARN):\n", + "with logger.console_level(logging.WARNING):\n", " driver.cartesian((0, 0, 0))\n", " with capture_dataframe(level=\"DEBUG\") as (handler, get_dataframe):\n", " driver.cartesian((0, 0, 1))\n", @@ -1197,7 +1195,7 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": null, "metadata": {}, "outputs": [ { @@ -1319,12 +1317,14 @@ } ], "source": [ - "with logger.console_level(logging.WARN):\n", + "with logger.console_level(logging.WARNING):\n", " driver.cartesian((0, 0, 0))\n", - " with capture_dataframe(level=\"DEBUG\") as (handler, get_dataframe):\n", - " with logger.filter_instrument(mag_x, handler=handler):\n", - " driver.cartesian((0, 0, 1))\n", - " df = get_dataframe()\n", + " with (\n", + " capture_dataframe(level=\"DEBUG\") as (handler, get_dataframe),\n", + " logger.filter_instrument(mag_x, handler=handler),\n", + " ):\n", + " driver.cartesian((0, 0, 1))\n", + " df = get_dataframe()\n", "df" ] }, diff --git a/pyproject.toml b/pyproject.toml index 4515823ee8db..c5c2bea2cf51 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -247,7 +247,8 @@ explicit-preview-rules = true # TID253 banned-module-level-imports # W pydocstyle # PLx pylint -select = [ +# extend-select = [ +extend-select = [ "E", "F", "PT025", "UP", "RUF", "YTT", "INP", "I", "G", "ISC", "TID253", "NPY", "PLE", "PLR", "PLC", "PLW", "W", @@ -260,7 +261,14 @@ select = [ # PLxxxx are pylint lints that generate a fair amount of warnings # it may be worth fixing some or these in the future # PYI036 disable until https://github.com/astral-sh/ruff/issues/9794 is fixed -ignore = ["E501", "G004", "PLR2004", "PLR0913", "PLR0911", "PLR0912", "PLR0915", "PLW0602", "PLW0603", "PLW2901", "PYI036"] +ignore = ["E501", "G004", "PLR2004", "PLR0913", "PLR0911", "PLR0912", "PLR0915", "PLW0602", "PLW0603", "PLW2901", "PYI036", + "B018", + "SIM118", # explicitly allowing keys() is fine + "DTZ007", "DTZ005", "BLE001", "S110", + "N999", "PIE804", + "DTZ006", + "TRY002", "TRY004" # these would require changing exception types +] # we want to explicitly use the micro symbol # not the greek letter diff --git a/src/qcodes/dataset/data_set_cache.py b/src/qcodes/dataset/data_set_cache.py index 210baac1d18e..b65c2da15d84 100644 --- a/src/qcodes/dataset/data_set_cache.py +++ b/src/qcodes/dataset/data_set_cache.py @@ -378,10 +378,7 @@ def _merge_data_single_param( ) elif new_values is not None or shape is not None: (merged_data, new_write_status) = _create_new_data_dict(new_values, shape) - elif existing_values is not None: - merged_data = existing_values - new_write_status = single_tree_write_status - elif shape is None and new_values is None: + elif existing_values is not None or (shape is None and new_values is None): merged_data = existing_values new_write_status = single_tree_write_status else: @@ -444,11 +441,13 @@ def _insert_into_data_dict( data[j] = np.atleast_1d(new_values[i]) return data, None else: - if existing_values.dtype.kind in ("U", "S"): + if ( + existing_values.dtype.kind in ("U", "S") + and new_values.dtype.itemsize > existing_values.dtype.itemsize + ): # string type arrays may be too small for the new data # read so rescale if needed. - if new_values.dtype.itemsize > existing_values.dtype.itemsize: - existing_values = existing_values.astype(new_values.dtype) + existing_values = existing_values.astype(new_values.dtype) n_values = new_values.size new_write_status = write_status + n_values if new_write_status > existing_values.size: diff --git a/src/qcodes/dataset/data_set_in_memory.py b/src/qcodes/dataset/data_set_in_memory.py index 9eb12971a350..241b789ba3bb 100644 --- a/src/qcodes/dataset/data_set_in_memory.py +++ b/src/qcodes/dataset/data_set_in_memory.py @@ -614,11 +614,13 @@ def add_metadata(self, tag: str, metadata: Any) -> None: def _add_to_dyn_column_if_in_db(self, tag: str, data: Any) -> None: if self._dataset_is_in_runs_table(): - with contextlib.closing( - conn_from_dbpath_or_conn(conn=None, path_to_db=self._path_to_db) - ) as conn: - with atomic(conn) as aconn: - add_data_to_dynamic_columns(aconn, self.run_id, {tag: data}) + with ( + contextlib.closing( + conn_from_dbpath_or_conn(conn=None, path_to_db=self._path_to_db) + ) as conn, + atomic(conn) as aconn, + ): + add_data_to_dynamic_columns(aconn, self.run_id, {tag: data}) @property def metadata(self) -> dict[str, Any]: diff --git a/src/qcodes/dataset/descriptions/detect_shapes.py b/src/qcodes/dataset/descriptions/detect_shapes.py index 76a6cdf22017..8897fc8868e5 100644 --- a/src/qcodes/dataset/descriptions/detect_shapes.py +++ b/src/qcodes/dataset/descriptions/detect_shapes.py @@ -90,11 +90,10 @@ def _get_shape_of_step(step: int | np.integer[Any] | Sized | npt.NDArray) -> int def _param_is_array_like(meas_param: ParameterBase) -> bool: - if isinstance(meas_param, (ArrayParameter, ParameterWithSetpoints)): - return True - elif isinstance(meas_param.vals, Arrays): - return True - return False + is_array_like = isinstance( + meas_param, (ArrayParameter, ParameterWithSetpoints) + ) or isinstance(meas_param.vals, Arrays) + return is_array_like def _get_shape_of_arrayparam(param: ParameterBase) -> tuple[int, ...]: diff --git a/src/qcodes/dataset/descriptions/rundescriber.py b/src/qcodes/dataset/descriptions/rundescriber.py index 33c1f2c5de36..697a47ea4419 100644 --- a/src/qcodes/dataset/descriptions/rundescriber.py +++ b/src/qcodes/dataset/descriptions/rundescriber.py @@ -108,9 +108,7 @@ def __eq__(self, other: object) -> bool: return False if self.interdeps != other.interdeps: return False - if self.shapes != other.shapes: - return False - return True + return self.shapes == other.shapes def __repr__(self) -> str: return f"RunDescriber({self.interdeps}, Shapes: {self._shapes})" diff --git a/src/qcodes/dataset/descriptions/versioning/v0.py b/src/qcodes/dataset/descriptions/versioning/v0.py index 4c73bda41af4..84cb1b5453f5 100644 --- a/src/qcodes/dataset/descriptions/versioning/v0.py +++ b/src/qcodes/dataset/descriptions/versioning/v0.py @@ -36,9 +36,7 @@ def __eq__(self, other: object) -> bool: return False ours = sorted(self.paramspecs, key=lambda ps: ps.name) theirs = sorted(other.paramspecs, key=lambda ps: ps.name) - if not ours == theirs: - return False - return True + return ours == theirs def _to_dict(self) -> InterDependenciesDict: """ diff --git a/src/qcodes/dataset/dond/do2d_retrace.py b/src/qcodes/dataset/dond/do2d_retrace.py index 833359d7135d..7961f2a08091 100644 --- a/src/qcodes/dataset/dond/do2d_retrace.py +++ b/src/qcodes/dataset/dond/do2d_retrace.py @@ -46,7 +46,7 @@ def do2d_retrace( after_inner_actions: ActionsT = (), measurement_name: str = "", exp: Experiment | None = None, - additional_setpoints: Sequence[ParameterBase] = tuple(), + additional_setpoints: Sequence[ParameterBase] = (), show_progress: bool | None = None, ) -> tuple[DataSetProtocol, DataSetProtocol]: """ diff --git a/src/qcodes/dataset/dond/do_2d.py b/src/qcodes/dataset/dond/do_2d.py index 0a39dc906c0b..55fe5fb566fc 100644 --- a/src/qcodes/dataset/dond/do_2d.py +++ b/src/qcodes/dataset/dond/do_2d.py @@ -68,7 +68,7 @@ def do2d( flush_columns: bool = False, do_plot: bool | None = None, use_threads: bool | None = None, - additional_setpoints: Sequence[ParameterBase] = tuple(), + additional_setpoints: Sequence[ParameterBase] = (), show_progress: bool | None = None, log_info: str | None = None, break_condition: BreakConditionT | None = None, @@ -214,9 +214,8 @@ def do2d( *additional_setpoints_data, ) - if callable(break_condition): - if break_condition(): - raise BreakConditionInterrupt("Break condition was met.") + if callable(break_condition) and break_condition(): + raise BreakConditionInterrupt("Break condition was met.") for action in after_inner_actions: action() diff --git a/src/qcodes/dataset/dond/do_nd.py b/src/qcodes/dataset/dond/do_nd.py index c3b6a304f178..c95b7700d4cb 100644 --- a/src/qcodes/dataset/dond/do_nd.py +++ b/src/qcodes/dataset/dond/do_nd.py @@ -593,7 +593,7 @@ def dond( do_plot: bool | None = None, show_progress: bool | None = None, use_threads: bool | None = None, - additional_setpoints: Sequence[ParameterBase] = tuple(), + additional_setpoints: Sequence[ParameterBase] = (), log_info: str | None = None, break_condition: BreakConditionT | None = None, dataset_dependencies: Mapping[str, Sequence[ParamMeasT]] | None = None, @@ -613,7 +613,7 @@ def dond( do_plot: bool | None = None, show_progress: bool | None = None, use_threads: bool | None = None, - additional_setpoints: Sequence[ParameterBase] = tuple(), + additional_setpoints: Sequence[ParameterBase] = (), log_info: str | None = None, break_condition: BreakConditionT | None = None, dataset_dependencies: Mapping[str, Sequence[ParamMeasT]] | None = None, @@ -633,7 +633,7 @@ def dond( do_plot: bool | None = None, show_progress: bool | None = None, use_threads: bool | None = None, - additional_setpoints: Sequence[ParameterBase] = tuple(), + additional_setpoints: Sequence[ParameterBase] = (), log_info: str | None = None, break_condition: BreakConditionT | None = None, dataset_dependencies: Mapping[str, Sequence[ParamMeasT]] | None = None, @@ -653,7 +653,7 @@ def dond( do_plot: bool | None = None, show_progress: bool | None = None, use_threads: bool | None = None, - additional_setpoints: Sequence[ParameterBase] = tuple(), + additional_setpoints: Sequence[ParameterBase] = (), log_info: str | None = None, break_condition: BreakConditionT | None = None, dataset_dependencies: Mapping[str, Sequence[ParamMeasT]] | None = None, @@ -835,9 +835,8 @@ def dond( *additional_setpoints_data, ) - if callable(break_condition): - if break_condition(): - raise BreakConditionInterrupt("Break condition was met.") + if callable(break_condition) and break_condition(): + raise BreakConditionInterrupt("Break condition was met.") finally: for datasaver in datasavers: ds, plot_axis, plot_color = _handle_plotting( @@ -883,9 +882,7 @@ def _parse_dond_arguments( sweep_instances: list[AbstractSweep | TogetherSweep] = [] params_meas: list[ParamMeasT | Sequence[ParamMeasT]] = [] for par in params: - if isinstance(par, AbstractSweep): - sweep_instances.append(par) - elif isinstance(par, TogetherSweep): + if isinstance(par, AbstractSweep | TogetherSweep): sweep_instances.append(par) else: params_meas.append(par) diff --git a/src/qcodes/dataset/dond/sweeps.py b/src/qcodes/dataset/dond/sweeps.py index efef85f1d973..041b42ba9ef6 100644 --- a/src/qcodes/dataset/dond/sweeps.py +++ b/src/qcodes/dataset/dond/sweeps.py @@ -25,7 +25,6 @@ def get_setpoints(self) -> npt.NDArray[T]: """ Returns an array of setpoint values for this sweep. """ - pass @property @abstractmethod @@ -33,7 +32,6 @@ def param(self) -> ParameterBase: """ Returns the Qcodes sweep parameter. """ - pass @property @abstractmethod @@ -41,7 +39,6 @@ def delay(self) -> float: """ Delay between two consecutive sweep points. """ - pass @property @abstractmethod @@ -49,7 +46,6 @@ def num_points(self) -> int: """ Number of sweep points. """ - pass @property @abstractmethod @@ -57,7 +53,6 @@ def post_actions(self) -> ActionsT: """ Actions to be performed after setting param to its setpoint. """ - pass @property def get_after_set(self) -> bool: diff --git a/src/qcodes/dataset/experiment_container.py b/src/qcodes/dataset/experiment_container.py index ad1f658e4a3c..d7b52e8c9997 100644 --- a/src/qcodes/dataset/experiment_container.py +++ b/src/qcodes/dataset/experiment_container.py @@ -400,7 +400,7 @@ def load_or_create_experiment( if "Experiment not found" in str(exception): experiment = new_experiment(experiment_name, sample_name, conn=conn) else: - raise exception + raise return experiment diff --git a/src/qcodes/dataset/export_config.py b/src/qcodes/dataset/export_config.py index 1a0a41def998..36dba5f38e31 100644 --- a/src/qcodes/dataset/export_config.py +++ b/src/qcodes/dataset/export_config.py @@ -80,9 +80,8 @@ def get_data_export_type( if isinstance(export_type, DataExportType): return export_type - elif export_type: - if hasattr(DataExportType, export_type.upper()): - return getattr(DataExportType, export_type.upper()) + elif export_type and hasattr(DataExportType, export_type.upper()): + return getattr(DataExportType, export_type.upper()) return None diff --git a/src/qcodes/dataset/exporters/export_to_csv.py b/src/qcodes/dataset/exporters/export_to_csv.py index e10068c49c35..6d07976dcf50 100644 --- a/src/qcodes/dataset/exporters/export_to_csv.py +++ b/src/qcodes/dataset/exporters/export_to_csv.py @@ -26,7 +26,7 @@ def dataframe_to_csv( ) -> None: import pandas as pd - dfs_to_save = list() + dfs_to_save = [] for parametername, df in dfdict.items(): if not single_file: dst = os.path.join(path, f"{parametername}.dat") diff --git a/src/qcodes/dataset/guid_helpers.py b/src/qcodes/dataset/guid_helpers.py index 7fb2e98b3b22..98ecc9582d97 100644 --- a/src/qcodes/dataset/guid_helpers.py +++ b/src/qcodes/dataset/guid_helpers.py @@ -89,7 +89,7 @@ def guids_from_list_str(s: str) -> tuple[str, ...] | None: """ if s == "": - return tuple() + return () try: validate_guid_format(s) @@ -111,7 +111,7 @@ def guids_from_list_str(s: str) -> tuple[str, ...] | None: if isinstance(parsed.value, str) and len(parsed.value) > 0: return (parsed.value,) else: - return tuple() + return () if not isinstance(parsed, (ast.List, ast.Tuple, ast.Set)): return None diff --git a/src/qcodes/dataset/guids.py b/src/qcodes/dataset/guids.py index 78bae87a0bed..7abbaf24e772 100644 --- a/src/qcodes/dataset/guids.py +++ b/src/qcodes/dataset/guids.py @@ -219,15 +219,12 @@ def filter_guids_by_parts( for guid in guids: guid_dict = parse_guid(guid) match = True - if sample_id is not None: - if guid_dict["sample"] != sample_id: - match = False - if location is not None: - if guid_dict["location"] != location: - match = False - if work_station is not None: - if guid_dict["work_station"] != work_station: - match = False + if sample_id is not None and guid_dict["sample"] != sample_id: + match = False + if location is not None and guid_dict["location"] != location: + match = False + if work_station is not None and guid_dict["work_station"] != work_station: + match = False if match: matched_guids.append(guid) diff --git a/src/qcodes/dataset/measurement_extensions.py b/src/qcodes/dataset/measurement_extensions.py index 11767772a49e..cdbc344c57c9 100644 --- a/src/qcodes/dataset/measurement_extensions.py +++ b/src/qcodes/dataset/measurement_extensions.py @@ -151,9 +151,7 @@ def parse_dond_into_args( raise ValueError("dond_into does not support TogetherSweeps") elif isinstance(par, Sequence): raise ValueError("dond_into does not support multiple datasets") - elif isinstance(par, ParameterBase) and par.gettable: - params_meas.append(par) - elif callable(par): + elif (isinstance(par, ParameterBase) and par.gettable) or callable(par): params_meas.append(par) return sweep_instances, params_meas @@ -161,7 +159,7 @@ def parse_dond_into_args( def dond_into( datasaver: DataSaver, *params: AbstractSweep | ParamMeasT, - additional_setpoints: Sequence[ParameterBase] = tuple(), + additional_setpoints: Sequence[ParameterBase] = (), ) -> None: """ A doNd-like utility function that writes gridded data to the supplied DataSaver diff --git a/src/qcodes/dataset/measurements.py b/src/qcodes/dataset/measurements.py index cb11a9246af3..06f463549320 100644 --- a/src/qcodes/dataset/measurements.py +++ b/src/qcodes/dataset/measurements.py @@ -539,7 +539,7 @@ def __init__( experiment: Experiment | None = None, station: Station | None = None, write_period: float | None = None, - interdeps: InterDependencies_ = InterDependencies_(), + interdeps: InterDependencies_ | None = None, name: str = "", subscribers: Sequence[SubscriberType] | None = None, parent_datasets: Sequence[Mapping[Any, Any]] = (), @@ -551,6 +551,8 @@ def __init__( parent_span: trace.Span | None = None, registered_parameters: Sequence[ParameterBase] = (), ) -> None: + if interdeps is None: + interdeps = InterDependencies_() if in_memory_cache is None: in_memory_cache = qc.config.dataset.in_memory_cache in_memory_cache = cast("bool", in_memory_cache) @@ -1125,9 +1127,9 @@ def _infer_paramtype(parameter: ParameterBase, paramtype: str | None) -> str: return_paramtype: str if paramtype is not None: # override with argument return_paramtype = paramtype - elif isinstance(parameter.vals, vals.Arrays): - return_paramtype = "array" - elif isinstance(parameter, ArrayParameter): + elif isinstance(parameter.vals, vals.Arrays) or isinstance( + parameter, ArrayParameter + ): return_paramtype = "array" elif isinstance(parameter.vals, vals.Strings): return_paramtype = "text" diff --git a/src/qcodes/dataset/plotting.py b/src/qcodes/dataset/plotting.py index bc381a6aece7..9b1965812da7 100644 --- a/src/qcodes/dataset/plotting.py +++ b/src/qcodes/dataset/plotting.py @@ -272,9 +272,9 @@ def plot_dataset( if len(data) == 2: # 1D PLOTTING if data[1]["name"] not in parameters: indices_to_remove.append(i) - elif len(data) == 3: # 2D PLOTTING - if data[2]["name"] not in parameters: - indices_to_remove.append(i) + elif len(data) == 3 and data[2]["name"] not in parameters: + # 2D PLOTTING + indices_to_remove.append(i) alldata = [d for (i, d) in enumerate(alldata) if i not in indices_to_remove] for data, ax, colorbar in zip(alldata, axeslist, colorbars): @@ -904,12 +904,15 @@ def _rescale_ticks_and_units( ax.set_ylabel(new_y_label) # for z aka colorbar axis - if cax is not None and len(data) > 2: - if not _is_string_valued_array(data[2]["data"]): - z_ticks_formatter, new_z_label = _make_rescaled_ticks_and_units(data[2]) - cax.set_label(new_z_label) - cax.formatter = z_ticks_formatter - cax.update_ticks() + if ( + cax is not None + and len(data) > 2 + and not _is_string_valued_array(data[2]["data"]) + ): + z_ticks_formatter, new_z_label = _make_rescaled_ticks_and_units(data[2]) + cax.set_label(new_z_label) + cax.formatter = z_ticks_formatter + cax.update_ticks() def _is_string_valued_array(values: npt.NDArray) -> bool: diff --git a/src/qcodes/dataset/sqlite/db_upgrades/__init__.py b/src/qcodes/dataset/sqlite/db_upgrades/__init__.py index 8af71f7cf291..c8e9d9b866ce 100644 --- a/src/qcodes/dataset/sqlite/db_upgrades/__init__.py +++ b/src/qcodes/dataset/sqlite/db_upgrades/__init__.py @@ -143,7 +143,7 @@ def perform_db_upgrade(conn: AtomicConnection, version: int = -1) -> None: current_version = get_user_version(conn) - show_progress_bar = not (_get_no_of_runs(conn) == 0) + show_progress_bar = _get_no_of_runs(conn) != 0 if current_version < version: log.info("Commencing database upgrade") diff --git a/src/qcodes/dataset/sqlite/queries.py b/src/qcodes/dataset/sqlite/queries.py index 4825f99f8bcd..f8c4864fc017 100644 --- a/src/qcodes/dataset/sqlite/queries.py +++ b/src/qcodes/dataset/sqlite/queries.py @@ -840,10 +840,9 @@ def mark_run_complete( is a noop. """ - if override is False: - if completed(conn=conn, run_id=run_id): - log.warning("Trying to mark a run completed that was already completed.") - return + if override is False and completed(conn=conn, run_id=run_id): + log.warning("Trying to mark a run completed that was already completed.") + return query = """ UPDATE @@ -1830,7 +1829,7 @@ def get_data_by_tag_and_table_name( ): data = None else: - raise e + raise return data @@ -1954,7 +1953,7 @@ def add_data_to_dynamic_columns( if str(e).startswith("duplicate"): update_columns(conn, row_id, table_name, data) else: - raise e + raise def get_experiment_name_from_experiment_id(conn: AtomicConnection, exp_id: int) -> str: @@ -2300,7 +2299,7 @@ def raw_time_to_str_time( def _check_if_table_found(conn: AtomicConnection, table_name: str) -> bool: query = "SELECT name FROM sqlite_master WHERE type='table' AND name=?" cursor = conn.cursor() - return not many_many(cursor.execute(query, (table_name,)), "name") == [] + return many_many(cursor.execute(query, (table_name,)), "name") != [] def _get_result_table_name_by_guid(conn: AtomicConnection, guid: str) -> str: diff --git a/src/qcodes/extensions/_refactor.py b/src/qcodes/extensions/_refactor.py index e9fc20c177a1..9b40054130c6 100644 --- a/src/qcodes/extensions/_refactor.py +++ b/src/qcodes/extensions/_refactor.py @@ -91,7 +91,6 @@ def visit_Arg(self, node: cst.Arg) -> None: self.annotations.parameter_class = e_value case cst.Arg(): _LOG.info("Unexpected node %s", str(node)) - pass def leave_Call(self, original_node: cst.Call, updated_node: cst.Call) -> cst.Call: call_name = _get_call_name(updated_node) diff --git a/src/qcodes/extensions/infer.py b/src/qcodes/extensions/infer.py index a88c98783d07..4cf661c9d3e7 100644 --- a/src/qcodes/extensions/infer.py +++ b/src/qcodes/extensions/infer.py @@ -220,7 +220,7 @@ def _merge_user_and_class_attrs( if alt_source_attrs is None: return InferAttrs.known_attrs() elif isinstance(alt_source_attrs, str): - return set.union(set((alt_source_attrs,)), set(InferAttrs.known_attrs())) + return set.union({alt_source_attrs}, set(InferAttrs.known_attrs())) else: return set.union(set(alt_source_attrs), set(InferAttrs.known_attrs())) @@ -264,11 +264,9 @@ def get_parent_instruments_from_chain_of_type( param_chain = get_parameter_chain(parameter) return tuple( - [ - param.instrument - for param in param_chain - if isinstance(param.instrument, instrument_type) - ] + param.instrument + for param in param_chain + if isinstance(param.instrument, instrument_type) ) diff --git a/src/qcodes/extensions/parameters/parameter_mixin_group_registry.py b/src/qcodes/extensions/parameters/parameter_mixin_group_registry.py index 05747ea2ba9a..472a75102a53 100644 --- a/src/qcodes/extensions/parameters/parameter_mixin_group_registry.py +++ b/src/qcodes/extensions/parameters/parameter_mixin_group_registry.py @@ -88,11 +88,10 @@ def group_names(self) -> list[str] | None: @group_names.setter def group_names(self, value: list[str] | None) -> None: - if value is not None: - if not isinstance(value, list) or not all( - isinstance(v, str) for v in value - ): - raise TypeError("group_names must be a list of strings or None.") + if value is not None and ( + not isinstance(value, list) or not all(isinstance(v, str) for v in value) + ): + raise TypeError("group_names must be a list of strings or None.") self._group_names = value @classmethod diff --git a/src/qcodes/instrument/channel.py b/src/qcodes/instrument/channel.py index 95baf3d91ca5..6e4f62c6b0fb 100644 --- a/src/qcodes/instrument/channel.py +++ b/src/qcodes/instrument/channel.py @@ -443,11 +443,10 @@ def multi_parameter( AttributeError: If no parameter with the given name exists. """ - if len(self) > 0: + if len(self) > 0 and name in self._channels[0].parameters: # Check if this is a valid parameter - if name in self._channels[0].parameters: - param = self._construct_multiparam(name) - return param + param = self._construct_multiparam(name) + return param raise AttributeError( f"'{self.__class__.__name__}' object has no parameter '{name}'" ) @@ -928,8 +927,6 @@ def validate(self, value: InstrumentChannel, context: str = "") -> None: class ChannelListValidator(ChannelTupleValidator): """Alias for backwards compatibility. Do not use""" - pass - class AutoLoadableInstrumentChannel(InstrumentChannel): """ diff --git a/src/qcodes/instrument/instrument.py b/src/qcodes/instrument/instrument.py index 8f2c36b39618..c53ba7e547b3 100644 --- a/src/qcodes/instrument/instrument.py +++ b/src/qcodes/instrument/instrument.py @@ -346,7 +346,7 @@ def exist(name: str, instrument_class: type[Instrument] | None = None) -> bool: if instrument_is_not_found: instrument_exists = False else: - raise exception + raise return instrument_exists @@ -360,16 +360,15 @@ def is_valid(instr_instance: Instrument) -> bool: instr_instance: Instance of an Instrument class or its subclass. """ - if ( + # note that it is important to call `instances` on the instance + # object instead of `Instrument` class, because instances of + # Instrument subclasses are recorded inside their subclasses; see + # `instances` for more information + is_valid_instrument_instance = ( isinstance(instr_instance, Instrument) and instr_instance in instr_instance.instances() - ): - # note that it is important to call `instances` on the instance - # object instead of `Instrument` class, because instances of - # Instrument subclasses are recorded inside their subclasses; see - # `instances` for more information - return True - return False + ) + return is_valid_instrument_instance # `write_raw` and `ask_raw` are the interface to hardware # # `write` and `ask` are standard wrappers to help with error reporting # @@ -398,7 +397,7 @@ def write(self, cmd: str) -> None: *e.args, f"writing {cmd!r} to {self!r}", ) - raise e + raise def write_raw(self, cmd: str) -> None: """ @@ -442,7 +441,7 @@ def ask(self, cmd: str) -> str: except Exception as e: e.args = (*e.args, f"asking {cmd!r} to {self!r}") - raise e + raise def ask_raw(self, cmd: str) -> str: """ diff --git a/src/qcodes/instrument/instrument_base.py b/src/qcodes/instrument/instrument_base.py index 52894a2e7284..7fe403f43073 100644 --- a/src/qcodes/instrument/instrument_base.py +++ b/src/qcodes/instrument/instrument_base.py @@ -385,9 +385,8 @@ def _get_component_by_name( component = component.get_component(remaining_name) remaining_name_parts = [] - if component is not None: - if len(remaining_name_parts) == 0: - return component + if component is not None and len(remaining_name_parts) == 0: + return component if len(remaining_name_parts) == 0: raise KeyError( @@ -529,7 +528,7 @@ def print_readable_snapshot( if unit != "": # corresponds to no unit msg += f"({unit})" # Truncate the message if it is longer than max length - if len(msg) > max_chars and not max_chars == -1: + if len(msg) > max_chars and max_chars != -1: msg = msg[0 : max_chars - 3] + "..." print(msg) diff --git a/src/qcodes/instrument/visa.py b/src/qcodes/instrument/visa.py index 66cdabd53ea9..f96bab558500 100644 --- a/src/qcodes/instrument/visa.py +++ b/src/qcodes/instrument/visa.py @@ -29,7 +29,7 @@ from qcodes.parameters.parameter import Parameter -VISA_LOGGER = ".".join((InstrumentBase.__module__, "com", "visa")) +VISA_LOGGER = f"{InstrumentBase.__module__}.com.visa" log = logging.getLogger(__name__) @@ -294,10 +294,10 @@ def _connect_and_handle_error( ) -> pyvisa.resources.MessageBasedResource: try: visa_handle = self._open_resource(address, visalib) - except Exception as e: + except Exception: self.visa_log.exception(f"Could not connect at {address}") self.close() - raise e + raise return visa_handle def _open_resource( diff --git a/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_PL068_P.py b/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_PL068_P.py index 6db141bbd099..b209e7059a7d 100644 --- a/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_PL068_P.py +++ b/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_PL068_P.py @@ -5,5 +5,3 @@ class AimTTiPL068P(AimTTi): """ This is the QCoDeS driver for the Aim TTi PL068-P series power supply. """ - - pass diff --git a/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_PL155_P.py b/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_PL155_P.py index c557d5f188b6..7cdda788d7ec 100644 --- a/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_PL155_P.py +++ b/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_PL155_P.py @@ -5,5 +5,3 @@ class AimTTiPL155P(AimTTi): """ This is the QCoDeS driver for the Aim TTi PL155-P series power supply. """ - - pass diff --git a/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_PL303QMD_P.py b/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_PL303QMD_P.py index 11120e9962a6..eeb9a8072757 100644 --- a/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_PL303QMD_P.py +++ b/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_PL303QMD_P.py @@ -5,5 +5,3 @@ class AimTTiPL303QMDP(AimTTi): """ This is the QCoDeS driver for the Aim TTi PL303QMD-P series power supply. """ - - pass diff --git a/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_PL303QMT_P.py b/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_PL303QMT_P.py index bb85f41c2ae1..51dcc4336789 100644 --- a/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_PL303QMT_P.py +++ b/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_PL303QMT_P.py @@ -5,5 +5,3 @@ class AimTTiPL303QMTP(AimTTi): """ This is the QCoDeS driver for the Aim TTi PL303QMT-P series power supply. """ - - pass diff --git a/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_PL303_P.py b/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_PL303_P.py index 34f809f93c93..7836d2719e81 100644 --- a/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_PL303_P.py +++ b/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_PL303_P.py @@ -5,5 +5,3 @@ class AimTTiPL303P(AimTTi): """ This is the QCoDeS driver for the Aim TTi PL303-P series power supply. """ - - pass diff --git a/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_PL601_P.py b/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_PL601_P.py index fcc75a78bcb3..1fa6af6737b0 100644 --- a/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_PL601_P.py +++ b/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_PL601_P.py @@ -5,5 +5,3 @@ class AimTTiPL601(AimTTi): """ This is the QCoDeS driver for the Aim TTi PL601-P series power supply. """ - - pass diff --git a/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_QL355_TP.py b/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_QL355_TP.py index e60573eec118..bc796aa5d5a9 100644 --- a/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_QL355_TP.py +++ b/src/qcodes/instrument_drivers/AimTTi/Aim_TTi_QL355_TP.py @@ -5,5 +5,3 @@ class AimTTiQL355TP(AimTTi): """ This is the QCoDeS driver for the Aim TTi QL355TP series power supply. """ - - pass diff --git a/src/qcodes/instrument_drivers/AimTTi/_AimTTi_PL_P.py b/src/qcodes/instrument_drivers/AimTTi/_AimTTi_PL_P.py index 21b6098be932..fc340e63ccfc 100644 --- a/src/qcodes/instrument_drivers/AimTTi/_AimTTi_PL_P.py +++ b/src/qcodes/instrument_drivers/AimTTi/_AimTTi_PL_P.py @@ -20,8 +20,6 @@ class NotKnownModel(Exception): An Error thrown when connecting to an unknown Aim TTi model """ - pass - class AimTTiChannel(InstrumentChannel): """ @@ -50,7 +48,7 @@ def __init__( self.channel = channel # The instrument can store up to ten configurations # internally. - self.set_up_store_slots = [i for i in range(0, 10)] + self.set_up_store_slots = [i for i in range(10)] self.volt: Parameter = self.add_parameter( "volt", diff --git a/src/qcodes/instrument_drivers/AlazarTech/ATS.py b/src/qcodes/instrument_drivers/AlazarTech/ATS.py index bba21e8424d6..8950660a7c75 100644 --- a/src/qcodes/instrument_drivers/AlazarTech/ATS.py +++ b/src/qcodes/instrument_drivers/AlazarTech/ATS.py @@ -569,14 +569,13 @@ def acquire( # noqa: D417 (missing args documentation) time_done_free_mem = time.perf_counter() # check if all parameters are up to date # Getting IDN is very slow so skip that - for _, p in self.parameters.items(): - if isinstance(p, TraceParameter): - if p.synced_to_card is False: - raise RuntimeError( - f"TraceParameter {p} not synced to " - f"Alazar card detected. Aborting. Data " - f"may be corrupt" - ) + for p in self.parameters.values(): + if isinstance(p, TraceParameter) and p.synced_to_card is False: + raise RuntimeError( + f"TraceParameter {p} not synced to " + f"Alazar card detected. Aborting. Data " + f"may be corrupt" + ) # Compute the total transfer time, and display performance information. end_time = time.perf_counter() @@ -854,13 +853,11 @@ def pre_start_capture(self) -> None: The Alazar instrument will call this method right before 'AlazarStartCapture' is called """ - pass def pre_acquire(self) -> None: """ This method is called immediately after 'AlazarStartCapture' is called """ - pass def handle_buffer( self, buffer: npt.NDArray, buffer_number: int | None = None @@ -901,7 +898,6 @@ def buffer_done_callback(self, buffers_completed: int) -> None: to local memory at the time of this callback. """ - pass class AcquisitionController(Instrument, AcquisitionInterface[Any], Generic[OutputType]): diff --git a/src/qcodes/instrument_drivers/AlazarTech/ATS9360.py b/src/qcodes/instrument_drivers/AlazarTech/ATS9360.py index 69cc66edba14..1a213352ef28 100644 --- a/src/qcodes/instrument_drivers/AlazarTech/ATS9360.py +++ b/src/qcodes/instrument_drivers/AlazarTech/ATS9360.py @@ -493,5 +493,3 @@ class AlazarTech_ATS9360(AlazarTechATS9360): """ Alias for backwards compatibility. Will eventually be deprecated and removed """ - - pass diff --git a/src/qcodes/instrument_drivers/AlazarTech/ATS9373.py b/src/qcodes/instrument_drivers/AlazarTech/ATS9373.py index 48697527c678..7f028da32a61 100644 --- a/src/qcodes/instrument_drivers/AlazarTech/ATS9373.py +++ b/src/qcodes/instrument_drivers/AlazarTech/ATS9373.py @@ -508,5 +508,3 @@ class AlazarTech_ATS9373(AlazarTechATS9373): """ Alias for backwards compatibility. Will eventually be deprecated and removed """ - - pass diff --git a/src/qcodes/instrument_drivers/AlazarTech/ATS9440.py b/src/qcodes/instrument_drivers/AlazarTech/ATS9440.py index 9c3e429d748e..e48b2455c7a7 100644 --- a/src/qcodes/instrument_drivers/AlazarTech/ATS9440.py +++ b/src/qcodes/instrument_drivers/AlazarTech/ATS9440.py @@ -409,5 +409,3 @@ class AlazarTech_ATS9440(AlazarTechATS9440): """ Alias for backwards compatibility. Will eventually be deprecated and removed """ - - pass diff --git a/src/qcodes/instrument_drivers/AlazarTech/ATS9870.py b/src/qcodes/instrument_drivers/AlazarTech/ATS9870.py index 7100901000d7..d11ff6dbe392 100644 --- a/src/qcodes/instrument_drivers/AlazarTech/ATS9870.py +++ b/src/qcodes/instrument_drivers/AlazarTech/ATS9870.py @@ -417,5 +417,3 @@ class AlazarTech_ATS9870(AlazarTechATS9870): """ Alias for backwards compatibility. Will eventually be deprecated and removed """ - - pass diff --git a/src/qcodes/instrument_drivers/AlazarTech/ATS_acquisition_controllers.py b/src/qcodes/instrument_drivers/AlazarTech/ATS_acquisition_controllers.py index 606722b8df75..d673abaaf424 100644 --- a/src/qcodes/instrument_drivers/AlazarTech/ATS_acquisition_controllers.py +++ b/src/qcodes/instrument_drivers/AlazarTech/ATS_acquisition_controllers.py @@ -102,7 +102,6 @@ def pre_acquire(self) -> None: # this could be used to start an Arbitrary Waveform Generator, etc... # using this method ensures that the contents are executed AFTER the # Alazar card starts listening for a trigger pulse - pass def handle_buffer( self, buffer: npt.NDArray, buffer_number: int | None = None @@ -178,5 +177,3 @@ class Demodulation_AcquisitionController(DemodulationAcquisitionController): """ Alias for backwards compatibility. Will eventually be deprecated and removed """ - - pass diff --git a/src/qcodes/instrument_drivers/CopperMountain/_M5xxx.py b/src/qcodes/instrument_drivers/CopperMountain/_M5xxx.py index 976a859a297a..6ee5d8c2fd19 100644 --- a/src/qcodes/instrument_drivers/CopperMountain/_M5xxx.py +++ b/src/qcodes/instrument_drivers/CopperMountain/_M5xxx.py @@ -595,7 +595,7 @@ def update_lin_traces(self) -> None: start = self.start() stop = self.stop() number_of_points = self.number_of_points() - for _, parameter in self.parameters.items(): + for parameter in self.parameters.values(): if isinstance(parameter, (FrequencySweepMagPhase)): try: parameter.set_sweep(start, stop, number_of_points) diff --git a/src/qcodes/instrument_drivers/Galil/dmc_41x3.py b/src/qcodes/instrument_drivers/Galil/dmc_41x3.py index 5ff4d9407d9b..c208d0e83e15 100644 --- a/src/qcodes/instrument_drivers/Galil/dmc_41x3.py +++ b/src/qcodes/instrument_drivers/Galil/dmc_41x3.py @@ -260,8 +260,6 @@ class VectorMode(GalilDMC4133VectorMode): Alias for backwards compatibility """ - pass - class GalilDMC4133Motor(InstrumentChannel["GalilDMC4133Controller"]): """ @@ -489,8 +487,6 @@ class Motor(GalilDMC4133Motor): Alias for backwards compatibility """ - pass - class GalilDMC4133Controller(GalilMotionController): """ @@ -579,7 +575,7 @@ def _get_absolute_position(self) -> dict[str, int]: """ Gets absolution position of the motors from the defined origin """ - result = dict() + result = {} data = self.ask("PA ?,?,?").split(" ") result["A"] = int(data[0][:-1]) result["B"] = int(data[1][:-1]) @@ -655,8 +651,6 @@ class DMC4133Controller(GalilDMC4133Controller): Alias for backwards compatibility """ - pass - class GalilDMC4133Arm: """ @@ -1177,5 +1171,3 @@ class Arm(GalilDMC4133Arm): """ Alias for backwards compatibility """ - - pass diff --git a/src/qcodes/instrument_drivers/Keithley/Keithley_2000.py b/src/qcodes/instrument_drivers/Keithley/Keithley_2000.py index 3d30cc36b37a..4177a72748b4 100644 --- a/src/qcodes/instrument_drivers/Keithley/Keithley_2000.py +++ b/src/qcodes/instrument_drivers/Keithley/Keithley_2000.py @@ -36,7 +36,7 @@ def _parse_output_string(s: str) -> str: def _parse_output_bool(value: str) -> bool: - return True if int(value) == 1 else False + return int(value) == 1 class Keithley2000(VisaInstrument): diff --git a/src/qcodes/instrument_drivers/Keithley/Keithley_2601B.py b/src/qcodes/instrument_drivers/Keithley/Keithley_2601B.py index 0965e1cf20e7..968229890b8c 100644 --- a/src/qcodes/instrument_drivers/Keithley/Keithley_2601B.py +++ b/src/qcodes/instrument_drivers/Keithley/Keithley_2601B.py @@ -5,5 +5,3 @@ class Keithley2601B(Keithley2600): """ QCoDeS driver for the Keithley 2601B Source-Meter """ - - pass diff --git a/src/qcodes/instrument_drivers/Keithley/Keithley_2602A.py b/src/qcodes/instrument_drivers/Keithley/Keithley_2602A.py index 84fc78beba27..7653d3116658 100644 --- a/src/qcodes/instrument_drivers/Keithley/Keithley_2602A.py +++ b/src/qcodes/instrument_drivers/Keithley/Keithley_2602A.py @@ -5,5 +5,3 @@ class Keithley2602A(Keithley2600): """ QCoDeS driver for the Keithley 2602A Source-Meter """ - - pass diff --git a/src/qcodes/instrument_drivers/Keithley/Keithley_2602B.py b/src/qcodes/instrument_drivers/Keithley/Keithley_2602B.py index 129a56249e6e..c4d33ae6ad7a 100644 --- a/src/qcodes/instrument_drivers/Keithley/Keithley_2602B.py +++ b/src/qcodes/instrument_drivers/Keithley/Keithley_2602B.py @@ -5,5 +5,3 @@ class Keithley2602B(Keithley2600): """ QCoDeS driver for the Keithley 2602B Source-Meter """ - - pass diff --git a/src/qcodes/instrument_drivers/Keithley/Keithley_2604B.py b/src/qcodes/instrument_drivers/Keithley/Keithley_2604B.py index 36d9bffaa794..374d0c5d1f16 100644 --- a/src/qcodes/instrument_drivers/Keithley/Keithley_2604B.py +++ b/src/qcodes/instrument_drivers/Keithley/Keithley_2604B.py @@ -5,5 +5,3 @@ class Keithley2604B(Keithley2600): """ QCoDeS driver for the Keithley 2604B Source-Meter """ - - pass diff --git a/src/qcodes/instrument_drivers/Keithley/Keithley_2611B.py b/src/qcodes/instrument_drivers/Keithley/Keithley_2611B.py index 684be904dce9..9b3beb0355fb 100644 --- a/src/qcodes/instrument_drivers/Keithley/Keithley_2611B.py +++ b/src/qcodes/instrument_drivers/Keithley/Keithley_2611B.py @@ -5,5 +5,3 @@ class Keithley2611B(Keithley2600): """ QCoDeS driver for the Keithley 2611B Source-Meter """ - - pass diff --git a/src/qcodes/instrument_drivers/Keithley/Keithley_2612B.py b/src/qcodes/instrument_drivers/Keithley/Keithley_2612B.py index ed99ec4ceb61..f80897ab7301 100644 --- a/src/qcodes/instrument_drivers/Keithley/Keithley_2612B.py +++ b/src/qcodes/instrument_drivers/Keithley/Keithley_2612B.py @@ -5,5 +5,3 @@ class Keithley2612B(Keithley2600): """ QCoDeS driver for the Keithley 2612B Source-Meter """ - - pass diff --git a/src/qcodes/instrument_drivers/Keithley/Keithley_2614B.py b/src/qcodes/instrument_drivers/Keithley/Keithley_2614B.py index 765fe96a8fef..255326370e3d 100644 --- a/src/qcodes/instrument_drivers/Keithley/Keithley_2614B.py +++ b/src/qcodes/instrument_drivers/Keithley/Keithley_2614B.py @@ -5,5 +5,3 @@ class Keithley2614B(Keithley2600): """ QCoDeS driver for the Keithley 2614B Source-Meter """ - - pass diff --git a/src/qcodes/instrument_drivers/Keithley/Keithley_2634B.py b/src/qcodes/instrument_drivers/Keithley/Keithley_2634B.py index 70282a793da6..17bd9123b059 100644 --- a/src/qcodes/instrument_drivers/Keithley/Keithley_2634B.py +++ b/src/qcodes/instrument_drivers/Keithley/Keithley_2634B.py @@ -5,5 +5,3 @@ class Keithley2634B(Keithley2600): """ QCoDeS driver for the Keithley 2634B Source-Meter """ - - pass diff --git a/src/qcodes/instrument_drivers/Keithley/Keithley_2635B.py b/src/qcodes/instrument_drivers/Keithley/Keithley_2635B.py index 04255c861cb9..18a6bd87ed69 100644 --- a/src/qcodes/instrument_drivers/Keithley/Keithley_2635B.py +++ b/src/qcodes/instrument_drivers/Keithley/Keithley_2635B.py @@ -5,5 +5,3 @@ class Keithley2635B(Keithley2600): """ QCoDeS driver for the Keithley 2635B Source-Meter """ - - pass diff --git a/src/qcodes/instrument_drivers/Keithley/Keithley_2636B.py b/src/qcodes/instrument_drivers/Keithley/Keithley_2636B.py index 8e60665fc543..ca60a8576cee 100644 --- a/src/qcodes/instrument_drivers/Keithley/Keithley_2636B.py +++ b/src/qcodes/instrument_drivers/Keithley/Keithley_2636B.py @@ -5,5 +5,3 @@ class Keithley2636B(Keithley2600): """ QCoDeS driver for the Keithley 2636B Source-Meter """ - - pass diff --git a/src/qcodes/instrument_drivers/Keithley/Keithley_3706A.py b/src/qcodes/instrument_drivers/Keithley/Keithley_3706A.py index a359685e5784..a148244c0712 100644 --- a/src/qcodes/instrument_drivers/Keithley/Keithley_3706A.py +++ b/src/qcodes/instrument_drivers/Keithley/Keithley_3706A.py @@ -222,9 +222,7 @@ def _warn_on_disengaged_interlocks(self, val: str) -> None: def _is_backplane_channel(self, channel_id: str) -> bool: if len(channel_id) != 4: raise Keithley3706AInvalidValue(f"{channel_id} is not a valid channel id") - if channel_id[1] == "9": - return True - return False + return channel_id[1] == "9" def exclusive_close(self, val: str) -> None: """ diff --git a/src/qcodes/instrument_drivers/Keithley/Keithley_s46.py b/src/qcodes/instrument_drivers/Keithley/Keithley_s46.py index 11b7901dc3a4..635dd8a53e5b 100644 --- a/src/qcodes/instrument_drivers/Keithley/Keithley_s46.py +++ b/src/qcodes/instrument_drivers/Keithley/Keithley_s46.py @@ -181,11 +181,11 @@ def __init__( ) self._available_channels.append(alias) - except RuntimeError as err: + except RuntimeError: # If we error on undesirable state we want to make sure # we also close the visa connection self.close() - raise err + raise @staticmethod def _get_closed_channels_parser(reply: str) -> list[str]: diff --git a/src/qcodes/instrument_drivers/Keysight/Infiniium.py b/src/qcodes/instrument_drivers/Keysight/Infiniium.py index e411beed9cff..e06c0fce3b99 100644 --- a/src/qcodes/instrument_drivers/Keysight/Infiniium.py +++ b/src/qcodes/instrument_drivers/Keysight/Infiniium.py @@ -500,8 +500,6 @@ class BoundMeasurement(KeysightInfiniiumBoundMeasurement): Alias for backwards compatibility """ - pass - class KeysightInfiniiumUnboundMeasurement(AbstractMeasurementSubsystem): def __init__( @@ -590,8 +588,6 @@ class UnboundMeasurement(KeysightInfiniiumUnboundMeasurement): Alias for backwards compatibility """ - pass - class KeysightInfiniiumFunction(InstrumentChannel): def __init__( @@ -719,8 +715,6 @@ class InfiniiumFunction(KeysightInfiniiumFunction): Alias for backwards compatibility """ - pass - class KeysightInfiniiumChannel(InstrumentChannel["KeysightInfiniium"]): def __init__( @@ -851,8 +845,6 @@ class InfiniiumChannel(KeysightInfiniiumChannel): Alias for backwards compatibility """ - pass - class KeysightInfiniium(VisaInstrument): """ @@ -1351,5 +1343,3 @@ class Infiniium(KeysightInfiniium): """ Alias for backwards compatibility """ - - pass diff --git a/src/qcodes/instrument_drivers/Keysight/Keysight_N6705B.py b/src/qcodes/instrument_drivers/Keysight/Keysight_N6705B.py index 6121239bbff8..1f6e976dba1d 100644 --- a/src/qcodes/instrument_drivers/Keysight/Keysight_N6705B.py +++ b/src/qcodes/instrument_drivers/Keysight/Keysight_N6705B.py @@ -106,8 +106,6 @@ def __init__( class N6705BChannel(KeysightN6705BChannel): """Alias for backwards compatibility""" - pass - class KeysightN6705B(VisaInstrument): default_terminator = "\n" diff --git a/src/qcodes/instrument_drivers/Keysight/KtM960x.py b/src/qcodes/instrument_drivers/Keysight/KtM960x.py index 326b22fe3d5a..9afe56e1f170 100644 --- a/src/qcodes/instrument_drivers/Keysight/KtM960x.py +++ b/src/qcodes/instrument_drivers/Keysight/KtM960x.py @@ -228,7 +228,7 @@ def _measure(self) -> tuple[ParamRawDataType, ...]: def get_errors(self) -> dict[int, str]: error_code = ctypes.c_int(-1) error_message = ctypes.create_string_buffer(256) - error_dict = dict() + error_dict = {} while error_code.value != 0: status = self._dll.KtM960x_error_query( self._session, ctypes.byref(error_code), error_message @@ -306,5 +306,3 @@ def close(self) -> None: ) class KtM960x(KeysightM960x): """Alias for backwards compatibility""" - - pass diff --git a/src/qcodes/instrument_drivers/Keysight/KtMAwg.py b/src/qcodes/instrument_drivers/Keysight/KtMAwg.py index 54054e88a8a4..0e3ae33778fb 100644 --- a/src/qcodes/instrument_drivers/Keysight/KtMAwg.py +++ b/src/qcodes/instrument_drivers/Keysight/KtMAwg.py @@ -342,7 +342,7 @@ def _catch_error(self, status: int) -> None: def get_errors(self) -> dict[int, str]: error_code = ctypes.c_int(-1) error_message = ctypes.create_string_buffer(256) - error_dict = dict() + error_dict = {} while error_code.value != 0: status = self._dll.KtMAwg_error_query( self._session, ctypes.byref(error_code), error_message @@ -421,8 +421,6 @@ def close(self) -> None: class KtMAWGChannel(KeysightM9336AAWGChannel): """Alias for backwards compatibility""" - pass - @deprecated( "KtMAwg is deprecated. Please use qcodes.instrument_drivers.Keysight.KeysightM9336A instead.", @@ -431,5 +429,3 @@ class KtMAWGChannel(KeysightM9336AAWGChannel): ) class KtMAwg(KeysightM9336A): """Alias for backwards compatibility""" - - pass diff --git a/src/qcodes/instrument_drivers/Keysight/keysight_34934a.py b/src/qcodes/instrument_drivers/Keysight/keysight_34934a.py index 2ac7a6e7dec9..b63169b7e197 100644 --- a/src/qcodes/instrument_drivers/Keysight/keysight_34934a.py +++ b/src/qcodes/instrument_drivers/Keysight/keysight_34934a.py @@ -1,4 +1,3 @@ -import logging import re from typing import TYPE_CHECKING @@ -65,7 +64,7 @@ def __init__( layout = self.ask(f"SYSTEM:MODule:TERMinal:TYPE? {self.slot}") self._is_locked = layout == "NONE" if self._is_locked: - logging.warning( + self.log.warning( f"For slot {slot}, no configuration module" f"connected, or safety interlock jumper removed. " "Making any connection is not allowed" @@ -80,7 +79,7 @@ def write(self, cmd: str) -> None: connections. There will be no effect when try to connect any channels. """ if self._is_locked: - logging.warning( + self.log.warning( "Warning: no configuration module connected, " "or safety interlock enabled. " "Making any connection is not allowed" diff --git a/src/qcodes/instrument_drivers/Keysight/keysight_34980a.py b/src/qcodes/instrument_drivers/Keysight/keysight_34980a.py index a5ffe4713c06..a71f6b60cf96 100644 --- a/src/qcodes/instrument_drivers/Keysight/keysight_34980a.py +++ b/src/qcodes/instrument_drivers/Keysight/keysight_34980a.py @@ -1,4 +1,3 @@ -import logging import re import warnings from functools import wraps @@ -148,7 +147,7 @@ def scan_slots(self) -> None: ) self.module[slot] = sub_module_no_driver self.add_submodule(sub_module_name, sub_module_no_driver) - logging.warning( + self.log.warning( f"can not find driver for {model_string} in slot {slot}" ) diff --git a/src/qcodes/instrument_drivers/Keysight/keysight_e4980a.py b/src/qcodes/instrument_drivers/Keysight/keysight_e4980a.py index 76fe3c0383b4..ac42fe729cf2 100644 --- a/src/qcodes/instrument_drivers/Keysight/keysight_e4980a.py +++ b/src/qcodes/instrument_drivers/Keysight/keysight_e4980a.py @@ -83,8 +83,6 @@ def get_raw(self) -> tuple[ParamRawDataType, ...]: class MeasurementPair(KeysightE4980AMeasurementPair): """Alias for backwards compatibility""" - pass - class KeysightE4980AMeasurements: """ @@ -162,8 +160,6 @@ class KeysightE4980AMeasurements: class E4980AMeasurements(KeysightE4980AMeasurements): """Alias for backwards compatibility""" - pass - class KeysightE4980ACorrection(InstrumentChannel): """ @@ -219,8 +215,6 @@ def __init__( class Correction4980A(KeysightE4980ACorrection): """Alias for backwards compatibility""" - pass - class KeysightE4980A(VisaInstrument): """ diff --git a/src/qcodes/instrument_drivers/Keysight/keysightb1500/KeysightB1500_base.py b/src/qcodes/instrument_drivers/Keysight/keysightb1500/KeysightB1500_base.py index a14786bcf7fb..b21d66aec84e 100644 --- a/src/qcodes/instrument_drivers/Keysight/keysightb1500/KeysightB1500_base.py +++ b/src/qcodes/instrument_drivers/Keysight/keysightb1500/KeysightB1500_base.py @@ -515,9 +515,9 @@ class IVSweepMeasurement( def __init__(self, name: str, instrument: KeysightB1500, **kwargs: Any): super().__init__( name, - names=tuple(["param1", "param2"]), - units=tuple(["A", "A"]), - labels=tuple(["Param1 Current", "Param2 Current"]), + names=("param1", "param2"), + units=("A", "A"), + labels=("Param1 Current", "Param2 Current"), shapes=((1,),) * 2, setpoint_names=(("Voltage",),) * 2, setpoint_labels=(("Voltage",),) * 2, @@ -704,7 +704,7 @@ def get_raw(self) -> tuple[tuple[float, ...], ...]: for channel_index in range(n_channels): parsed_data_items = [ parsed_data[i][channel_index::n_all_data_channels] - for i in range(0, n_items_per_data_point) + for i in range(n_items_per_data_point) ] single_channel_data = _FMTResponse(*parsed_data_items) convert_dummy_val_to_nan(single_channel_data) @@ -720,7 +720,7 @@ def get_raw(self) -> tuple[tuple[float, ...], ...]: source_voltage_index = n_channels parsed_source_voltage_items = [ parsed_data[i][source_voltage_index::n_all_data_channels] - for i in range(0, n_items_per_data_point) + for i in range(n_items_per_data_point) ] self.source_voltage = _FMTResponse(*parsed_source_voltage_items) diff --git a/src/qcodes/instrument_drivers/Keysight/keysightb1500/KeysightB1500_module.py b/src/qcodes/instrument_drivers/Keysight/keysightb1500/KeysightB1500_module.py index 479399c571b2..004fcfda0bc6 100644 --- a/src/qcodes/instrument_drivers/Keysight/keysightb1500/KeysightB1500_module.py +++ b/src/qcodes/instrument_drivers/Keysight/keysightb1500/KeysightB1500_module.py @@ -196,17 +196,19 @@ def fixed_negative_float(response: str) -> float: decimal = decimal.replace("-", "") - output = ".".join([number, decimal]) + output = f"{number}.{decimal}" return float(output) _dcorr_labels_units_map = { - constants.DCORR.Mode.Cp_G: dict( - primary=dict(label="Cp", unit="F"), secondary=dict(label="G", unit="S") - ), - constants.DCORR.Mode.Ls_Rs: dict( - primary=dict(label="Ls", unit="H"), secondary=dict(label="Rs", unit="Ω") - ), + constants.DCORR.Mode.Cp_G: { + "primary": {"label": "Cp", "unit": "F"}, + "secondary": {"label": "G", "unit": "S"}, + }, + constants.DCORR.Mode.Ls_Rs: { + "primary": {"label": "Ls", "unit": "H"}, + "secondary": {"label": "Rs", "unit": "Ω"}, + }, } diff --git a/src/qcodes/instrument_drivers/Keysight/keysightb1500/KeysightB1511B.py b/src/qcodes/instrument_drivers/Keysight/keysightb1500/KeysightB1511B.py index 521299da7e2e..3b72851f578d 100644 --- a/src/qcodes/instrument_drivers/Keysight/keysightb1500/KeysightB1511B.py +++ b/src/qcodes/instrument_drivers/Keysight/keysightb1500/KeysightB1511B.py @@ -120,5 +120,3 @@ class B1511B(KeysightB1511B): """ Alias for backwards compatibility """ - - pass diff --git a/src/qcodes/instrument_drivers/Keysight/keysightb1500/KeysightB1517A.py b/src/qcodes/instrument_drivers/Keysight/keysightb1500/KeysightB1517A.py index 774d7380ab94..be98ecbe2e44 100644 --- a/src/qcodes/instrument_drivers/Keysight/keysightb1500/KeysightB1517A.py +++ b/src/qcodes/instrument_drivers/Keysight/keysightb1500/KeysightB1517A.py @@ -707,8 +707,6 @@ class IVSweeper(KeysightB1500IVSweeper): Alias for backwards compatibility """ - pass - class _ParameterWithStatus( Parameter[ParameterDataTypeVar, "KeysightB1517A"], Generic[ParameterDataTypeVar] @@ -1184,20 +1182,25 @@ def source_config( range """ - if min_compliance_range is not None: - if isinstance(min_compliance_range, type(output_range)): - raise TypeError( - "When forcing voltage, min_compliance_range must be an " - "current output range (and vice versa)." - ) + if min_compliance_range is not None and isinstance( + min_compliance_range, type(output_range) + ): + raise TypeError( + "When forcing voltage, min_compliance_range must be an " + "current output range (and vice versa)." + ) - if isinstance(output_range, VOutputRange): - if output_range not in self._valid_v_output_ranges: - raise RuntimeError("Invalid Source Voltage Output Range") + if ( + isinstance(output_range, VOutputRange) + and output_range not in self._valid_v_output_ranges + ): + raise RuntimeError("Invalid Source Voltage Output Range") - if isinstance(output_range, IOutputRange): - if output_range not in self._valid_i_output_ranges: - raise RuntimeError("Invalid Source Current Output Range") + if ( + isinstance(output_range, IOutputRange) + and output_range not in self._valid_i_output_ranges + ): + raise RuntimeError("Invalid Source Current Output Range") self._source_config = { "output_range": output_range, @@ -1429,5 +1432,3 @@ class B1517A(KeysightB1517A): """ Alias for backwards compatibility """ - - pass diff --git a/src/qcodes/instrument_drivers/Keysight/keysightb1500/KeysightB1520A.py b/src/qcodes/instrument_drivers/Keysight/keysightb1500/KeysightB1520A.py index 686766e40e3c..14062ccd3625 100644 --- a/src/qcodes/instrument_drivers/Keysight/keysightb1500/KeysightB1520A.py +++ b/src/qcodes/instrument_drivers/Keysight/keysightb1500/KeysightB1520A.py @@ -462,8 +462,6 @@ class CVSweeper(KeysightB1500CVSweeper): Alias for backwards compatibility """ - pass - class KeysightB1520A(KeysightB1500Module): """ @@ -823,14 +821,13 @@ def sign(s: float) -> float: end_value = self.cv_sweep.sweep_end() step_value = self.cv_sweep.sweep_steps() mode = self.cv_sweep.sweep_mode() - if mode in (2, 4): - if not sign(start_value) == sign(end_value): - if sign(start_value) == 0: - start_value = sign(start_value) * 0.005 # resolution - elif sign(end_value) == 0: - end_value = sign(end_value) * 0.005 # resolution - else: - raise AssertionError("Polarity of start and end is not same.") + if mode in (2, 4) and sign(start_value) != sign(end_value): + if sign(start_value) == 0: + start_value = sign(start_value) * 0.005 # resolution + elif sign(end_value) == 0: + end_value = sign(end_value) * 0.005 # resolution + else: + raise AssertionError("Polarity of start and end is not same.") def linear_sweep(start: float, end: float, steps: int) -> tuple[float, ...]: sweep_val = np.linspace(start, end, steps).flatten().tolist() @@ -1162,8 +1159,6 @@ class B1520A(KeysightB1520A): Alias for backwards compatiblitly """ - pass - class KeysightB1500CVSweepMeasurement( MultiParameter[tuple[tuple[float, ...], tuple[float, ...]], KeysightB1520A], @@ -1235,16 +1230,16 @@ def get_raw(self) -> tuple[tuple[float, ...], tuple[float, ...]]: parsed_data = fmt_response_base_parser(raw_data) if len(set(parsed_data.type)) == 2: - self.param1 = _FMTResponse(*(parsed_data[i][::2] for i in range(0, 4))) - self.param2 = _FMTResponse(*(parsed_data[i][1::2] for i in range(0, 4))) + self.param1 = _FMTResponse(*(parsed_data[i][::2] for i in range(4))) + self.param2 = _FMTResponse(*(parsed_data[i][1::2] for i in range(4))) self.shapes = ((num_steps,),) * 2 self.setpoints = ((self.instrument.cv_sweep_voltages(),),) * 2 else: - self.param1 = _FMTResponse(*(parsed_data[i][::4] for i in range(0, 4))) - self.param2 = _FMTResponse(*(parsed_data[i][1::4] for i in range(0, 4))) - self.ac_voltage = _FMTResponse(*(parsed_data[i][2::4] for i in range(0, 4))) - self.dc_voltage = _FMTResponse(*(parsed_data[i][3::4] for i in range(0, 4))) + self.param1 = _FMTResponse(*(parsed_data[i][::4] for i in range(4))) + self.param2 = _FMTResponse(*(parsed_data[i][1::4] for i in range(4))) + self.ac_voltage = _FMTResponse(*(parsed_data[i][2::4] for i in range(4))) + self.dc_voltage = _FMTResponse(*(parsed_data[i][3::4] for i in range(4))) self.shapes = ((len(self.dc_voltage.value),),) * 2 self.setpoints = ((self.dc_voltage.value,),) * 2 @@ -1277,8 +1272,6 @@ class CVSweepMeasurement(KeysightB1500CVSweepMeasurement): Alias for backwards compatibility """ - pass - class KeysightB1500Correction(InstrumentChannel["KeysightB1520A"]): """ @@ -1454,8 +1447,6 @@ class Correction(KeysightB1500Correction): Alias for backwards compatibility """ - pass - class KeysightB1500FrequencyList(InstrumentChannel["KeysightB1500Correction"]): """ @@ -1520,5 +1511,3 @@ class FrequencyList(KeysightB1500FrequencyList): """ Alias for backwards compatibility """ - - pass diff --git a/src/qcodes/instrument_drivers/Keysight/keysightb1500/KeysightB1530A.py b/src/qcodes/instrument_drivers/Keysight/keysightb1500/KeysightB1530A.py index 72b648eeb1e7..c894a078851c 100644 --- a/src/qcodes/instrument_drivers/Keysight/keysightb1500/KeysightB1530A.py +++ b/src/qcodes/instrument_drivers/Keysight/keysightb1500/KeysightB1530A.py @@ -56,5 +56,3 @@ class B1530A(KeysightB1530A): """ Alias for backwards compatibility """ - - pass diff --git a/src/qcodes/instrument_drivers/Keysight/private/Keysight_344xxA_submodules.py b/src/qcodes/instrument_drivers/Keysight/private/Keysight_344xxA_submodules.py index 4166adca35f8..c1cbab948ce6 100644 --- a/src/qcodes/instrument_drivers/Keysight/private/Keysight_344xxA_submodules.py +++ b/src/qcodes/instrument_drivers/Keysight/private/Keysight_344xxA_submodules.py @@ -1138,7 +1138,7 @@ def _licenses(self) -> "Sequence[str]": licenses_raw = self.ask("SYST:LIC:CAT?") licenses_list = [x.strip('"') for x in licenses_raw.split(",")] return licenses_list - return tuple() + return () def _options(self) -> tuple[str, ...]: """ @@ -1154,7 +1154,7 @@ def _options(self) -> tuple[str, ...]: options_raw = self.ask("*OPT?") options_list = [opt for opt in options_raw.split(",") if opt != "0"] return tuple(options_list) - return tuple() + return () def _get_parameter(self, sense_function: str = "DC Voltage") -> float: """ @@ -1169,9 +1169,8 @@ def _get_parameter(self, sense_function: str = "DC Voltage") -> float: The float value of the parameter. """ - with self.sense_function.set_to(sense_function): - with self.sample.count.set_to(1): - response = self.ask("READ?") + with self.sense_function.set_to(sense_function), self.sample.count.set_to(1): + response = self.ask("READ?") if float(response) >= 9.9e37: return np.inf diff --git a/src/qcodes/instrument_drivers/Lakeshore/Lakeshore_model_325.py b/src/qcodes/instrument_drivers/Lakeshore/Lakeshore_model_325.py index 6626a93ff903..2e7b353c3920 100644 --- a/src/qcodes/instrument_drivers/Lakeshore/Lakeshore_model_325.py +++ b/src/qcodes/instrument_drivers/Lakeshore/Lakeshore_model_325.py @@ -46,7 +46,7 @@ def strip(strings: "Iterable[str]") -> tuple[str, ...]: # Meta data lines contain a colon metadata_lines = takewhile(lambda s: ":" in s, lines) # Data from the file is collected in the following dict - file_data: dict[str, dict[str, Any]] = dict() + file_data: dict[str, dict[str, Any]] = {} # Capture meta data parsed_lines = [strip(line.split(":")) for line in metadata_lines] file_data["metadata"] = {key: value for key, value in parsed_lines} diff --git a/src/qcodes/instrument_drivers/Minicircuits/RC_SP4T.py b/src/qcodes/instrument_drivers/Minicircuits/RC_SP4T.py index 69f75942a82a..b33c892196cb 100644 --- a/src/qcodes/instrument_drivers/Minicircuits/RC_SP4T.py +++ b/src/qcodes/instrument_drivers/Minicircuits/RC_SP4T.py @@ -15,8 +15,6 @@ class MC_channel(MiniCircuitsRCSP4TChannel): Alias for backwards compatibility """ - pass - @deprecated( "RC_SP4T is deprecated. Please use qcodes.instrument_drivers.Minicircuits.MiniCircuitsRCSP4T instead.", @@ -27,5 +25,3 @@ class RC_SP4T(MiniCircuitsRCSP4T): """ Alias for backwards compatibility """ - - pass diff --git a/src/qcodes/instrument_drivers/Minicircuits/RC_SPDT.py b/src/qcodes/instrument_drivers/Minicircuits/RC_SPDT.py index 49d7a29575da..de92154707a2 100644 --- a/src/qcodes/instrument_drivers/Minicircuits/RC_SPDT.py +++ b/src/qcodes/instrument_drivers/Minicircuits/RC_SPDT.py @@ -15,8 +15,6 @@ class MC_channel(MiniCircuitsRCSPDTChannel): Alias for backwards compatibility """ - pass - @deprecated( "RC_SPDT is deprecated. Please use qcodes.instrument_drivers.Minicircuits.MiniCircuitsRCSPDT instead.", @@ -27,5 +25,3 @@ class RC_SPDT(MiniCircuitsRCSPDT): """ Alias for backwards compatibility """ - - pass diff --git a/src/qcodes/instrument_drivers/Minicircuits/RUDAT_13G_90.py b/src/qcodes/instrument_drivers/Minicircuits/RUDAT_13G_90.py index 8a55b5e61a05..9e095b8cb0fe 100644 --- a/src/qcodes/instrument_drivers/Minicircuits/RUDAT_13G_90.py +++ b/src/qcodes/instrument_drivers/Minicircuits/RUDAT_13G_90.py @@ -17,8 +17,6 @@ class RUDAT_13G_90(MiniCircuitsRudat13G90Base): """Alias for backwards compatibility.""" - pass - @deprecated( "RUDAT_13G_90_USB is deprecated. Please use qcodes.instrument_drivers.Minicircuits.MiniCircuitsRudat13G90Usb instead.", @@ -27,5 +25,3 @@ class RUDAT_13G_90(MiniCircuitsRudat13G90Base): ) class RUDAT_13G_90_USB(MiniCircuitsRudat13G90Usb): """Alias for backwards compatibility.""" - - pass diff --git a/src/qcodes/instrument_drivers/Minicircuits/USB_SPDT.py b/src/qcodes/instrument_drivers/Minicircuits/USB_SPDT.py index ed76cc644804..972a0b2e038a 100644 --- a/src/qcodes/instrument_drivers/Minicircuits/USB_SPDT.py +++ b/src/qcodes/instrument_drivers/Minicircuits/USB_SPDT.py @@ -18,8 +18,6 @@ class SwitchChannelUSB(MiniCircuitsUsbSPDTSwitchChannel): Alias for backwards compatibility """ - pass - @deprecated( "USB_SPDT is deprecated. Please use qcodes.instrument_drivers.Minicircuits.MiniCircuitsUsbSPDT instead.", @@ -30,5 +28,3 @@ class USB_SPDT(MiniCircuitsUsbSPDT): """ Alias for backwards compatibility """ - - pass diff --git a/src/qcodes/instrument_drivers/QDev/QDac_channels.py b/src/qcodes/instrument_drivers/QDev/QDac_channels.py index 7d0a8fd0dd4f..b51882c3788e 100644 --- a/src/qcodes/instrument_drivers/QDev/QDac_channels.py +++ b/src/qcodes/instrument_drivers/QDev/QDac_channels.py @@ -820,5 +820,3 @@ class QDac(QDevQDac): """ Backwards compatibility alias for QDevQDac driver """ - - pass diff --git a/src/qcodes/instrument_drivers/QuantumDesign/DynaCoolPPMS/DynaCool.py b/src/qcodes/instrument_drivers/QuantumDesign/DynaCoolPPMS/DynaCool.py index 080ba979864d..1ce2d863a8c4 100644 --- a/src/qcodes/instrument_drivers/QuantumDesign/DynaCoolPPMS/DynaCool.py +++ b/src/qcodes/instrument_drivers/QuantumDesign/DynaCoolPPMS/DynaCool.py @@ -390,7 +390,7 @@ def _field_setter( The combined set function for the three field parameters, field_setpoint, field_rate, and field_approach """ - temporary_values = list(self.parameters[p].raw_value for p in self.field_params) + temporary_values = [self.parameters[p].raw_value for p in self.field_params] values = cast("list[int | float]", temporary_values) values[self.field_params.index(param)] = value @@ -424,7 +424,7 @@ def _temp_setter( The setter function for the temperature parameters. All three are set with the same call to the instrument API """ - temp_values = list(self.parameters[par].raw_value for par in self.temp_params) + temp_values = [self.parameters[par].raw_value for par in self.temp_params] values = cast("list[int | float]", temp_values) values[self.temp_params.index(param)] = value diff --git a/src/qcodes/instrument_drivers/QuantumDesign/DynaCoolPPMS/private/commandhandler.py b/src/qcodes/instrument_drivers/QuantumDesign/DynaCoolPPMS/private/commandhandler.py index 0aeae6e5f493..d99b71d0764e 100644 --- a/src/qcodes/instrument_drivers/QuantumDesign/DynaCoolPPMS/private/commandhandler.py +++ b/src/qcodes/instrument_drivers/QuantumDesign/DynaCoolPPMS/private/commandhandler.py @@ -135,7 +135,7 @@ def err_func() -> int: is_query = True else: cmd = self._sets[cmd_head] - args = list(float(arg) for arg in cmd_str[5:].split(", ")) + args = [float(arg) for arg in cmd_str[5:].split(", ")] is_query = False return CmdArgs(cmd=cmd, args=args), is_query @@ -169,7 +169,7 @@ def __call__(self, cmd: str) -> str: if is_query: # read out the mutated values # (win32 reverses the order) - vals = list(arg.value for arg in cmd_and_args.args) + vals = [arg.value for arg in cmd_and_args.args] vals.reverse() # reset the value variables for good measures for arg in cmd_and_args.args: diff --git a/src/qcodes/instrument_drivers/QuantumDesign/DynaCoolPPMS/private/server.py b/src/qcodes/instrument_drivers/QuantumDesign/DynaCoolPPMS/private/server.py index 921d5b0878ac..0494c21f161b 100644 --- a/src/qcodes/instrument_drivers/QuantumDesign/DynaCoolPPMS/private/server.py +++ b/src/qcodes/instrument_drivers/QuantumDesign/DynaCoolPPMS/private/server.py @@ -45,10 +45,9 @@ def run_server() -> None: read_sockets = select.select(list(socket_dict.keys()), [], [], 1)[0] # Keyboard - if kbhit(): - if ord(getch()) == 27: - print("Server exiting") - break + if kbhit() and ord(getch()) == 27: + print("Server exiting") + break for sock in read_sockets: # New connection diff --git a/src/qcodes/instrument_drivers/american_magnetics/AMI430_visa.py b/src/qcodes/instrument_drivers/american_magnetics/AMI430_visa.py index 3d701d54b129..301712611dc5 100644 --- a/src/qcodes/instrument_drivers/american_magnetics/AMI430_visa.py +++ b/src/qcodes/instrument_drivers/american_magnetics/AMI430_visa.py @@ -374,24 +374,22 @@ def _can_start_ramping(self) -> bool: Check the current state of the magnet to see if we can start ramping """ if self.is_quenched(): - logging.error(f"{__name__}: Could not ramp because of quench") + self.log.error(f"{__name__}: Could not ramp because of quench") return False if self.switch_heater.in_persistent_mode(): - logging.error(f"{__name__}: Could not ramp because persistent") + self.log.error(f"{__name__}: Could not ramp because persistent") return False state = self.ramping_state() if state == "ramping": # If we don't have a persistent switch, or it's warm - if not self.switch_heater.enabled(): - return True - elif self.switch_heater.state(): + if not self.switch_heater.enabled() or self.switch_heater.state(): return True elif state in ["holding", "paused", "at zero current"]: return True - logging.error(f"{__name__}: Could not ramp, state: {state}") + self.log.error(f"{__name__}: Could not ramp, state: {state}") return False def set_field( @@ -431,9 +429,8 @@ def set_field( self.write(f"CONF:FIELD:TARG {value}") # If we have a persistent switch, make sure it is resistive - if self.switch_heater.enabled(): - if not self.switch_heater.state(): - raise AMI430Exception("Switch heater is not on") + if self.switch_heater.enabled() and not self.switch_heater.state(): + raise AMI430Exception("Switch heater is not on") self.ramp() # Check if we want to block @@ -558,7 +555,7 @@ def _update_units( def write_raw(self, cmd: str) -> None: try: super().write_raw(cmd) - except VisaIOError as err: + except VisaIOError: # The ami communication has found to be unstable # so we retry the communication here msg = f"Got VisaIOError while writing {cmd} to instrument." @@ -570,12 +567,12 @@ def write_raw(self, cmd: str) -> None: self.device_clear() super().write_raw(cmd) else: - raise err + raise def ask_raw(self, cmd: str) -> str: try: result = super().ask_raw(cmd) - except VisaIOError as err: + except VisaIOError: # The ami communication has found to be unstable # so we retry the communication here msg = f"Got VisaIOError while asking the instrument: {cmd}" @@ -587,7 +584,7 @@ def ask_raw(self, cmd: str) -> str: self.device_clear() result = super().ask_raw(cmd) else: - raise err + raise return result @@ -1012,7 +1009,7 @@ def _verify_safe_setpoint( return bool(np.linalg.norm(setpoint_values) < self._field_limit) answer = any( - [limit_function(*setpoint_values) for limit_function in self._field_limit] + limit_function(*setpoint_values) for limit_function in self._field_limit ) return answer diff --git a/src/qcodes/instrument_drivers/cryomagnetics/_cryomagnetics4g.py b/src/qcodes/instrument_drivers/cryomagnetics/_cryomagnetics4g.py index 0f652be3017a..905de6f35bbf 100644 --- a/src/qcodes/instrument_drivers/cryomagnetics/_cryomagnetics4g.py +++ b/src/qcodes/instrument_drivers/cryomagnetics/_cryomagnetics4g.py @@ -445,7 +445,7 @@ def _initialize_max_current_limits(self) -> None: def write_raw(self, cmd: str) -> None: try: super().write_raw(cmd) - except VisaIOError as err: + except VisaIOError: # The ami communication has found to be unstable # so we retry the communication here msg = f"Got VisaIOError while writing {cmd} to instrument." @@ -457,12 +457,12 @@ def write_raw(self, cmd: str) -> None: self.device_clear() super().write_raw(cmd) else: - raise err + raise def ask_raw(self, cmd: str) -> str: try: result = super().ask_raw(cmd) - except VisaIOError as err: + except VisaIOError: # The communication has found to be unstable # so we retry the communication here msg = f"Got VisaIOError while asking the instrument: {cmd}" @@ -474,5 +474,5 @@ def ask_raw(self, cmd: str) -> str: self.device_clear() result = super().ask_raw(cmd) else: - raise err + raise return result diff --git a/src/qcodes/instrument_drivers/mock_instruments/__init__.py b/src/qcodes/instrument_drivers/mock_instruments/__init__.py index 4bf8a9b914cb..c71467fed361 100644 --- a/src/qcodes/instrument_drivers/mock_instruments/__init__.py +++ b/src/qcodes/instrument_drivers/mock_instruments/__init__.py @@ -1083,7 +1083,7 @@ class MockField(DummyBase): def __init__( self, name: str, - vals: Numbers = Numbers(min_value=-1.0, max_value=1.0), + vals: Numbers | None = None, **kwargs: Unpack[InstrumentBaseKWArgs], ): """Mock instrument for emulating a magnetic field axis @@ -1096,6 +1096,8 @@ def __init__( """ super().__init__(name=name, **kwargs) self._field = 0.0 + if vals is None: + vals = Numbers(min_value=-1.0, max_value=1.0) self.field: Parameter = self.add_parameter( "field", parameter_class=Parameter, diff --git a/src/qcodes/instrument_drivers/oxford/MercuryiPS_VISA.py b/src/qcodes/instrument_drivers/oxford/MercuryiPS_VISA.py index 0f48e5b62e69..0d244ab8b98a 100644 --- a/src/qcodes/instrument_drivers/oxford/MercuryiPS_VISA.py +++ b/src/qcodes/instrument_drivers/oxford/MercuryiPS_VISA.py @@ -302,8 +302,6 @@ class MercuryWorkerPS(OxfordMercuryWorkerPS): Alias for backwards compatibility """ - pass - class OxfordMercuryiPS(VisaInstrument): """ @@ -683,9 +681,8 @@ def ramp(self, mode: str = "safe") -> None: for cur, worker in zip(meas_vals, self.submodules.values()): if not isinstance(worker, OxfordMercuryWorkerPS): raise RuntimeError(f"Expected a MercuryWorkerPS but got {type(worker)}") - if worker.field_target() != cur: - if worker.field_ramp_rate() == 0: - raise ValueError(f"Can not ramp {worker}; ramp rate set to zero!") + if worker.field_target() != cur and worker.field_ramp_rate() == 0: + raise ValueError(f"Can not ramp {worker}; ramp rate set to zero!") # then the actual ramp { @@ -739,5 +736,3 @@ def ask(self, cmd: str) -> str: ) class MercuryiPS(OxfordMercuryiPS): """Alias for backwards compatibility""" - - pass diff --git a/src/qcodes/instrument_drivers/oxford/triton.py b/src/qcodes/instrument_drivers/oxford/triton.py index 0d240239d98c..5029fad29c48 100644 --- a/src/qcodes/instrument_drivers/oxford/triton.py +++ b/src/qcodes/instrument_drivers/oxford/triton.py @@ -1,5 +1,4 @@ import configparser -import logging import re from functools import partial from time import sleep @@ -274,7 +273,7 @@ def __init__( try: self._get_named_channels() except Exception: - logging.warning("Ignored an error in _get_named_channels\n", exc_info=True) + self.log.warning("Ignored an error in _get_named_channels\n", exc_info=True) self.connect_message() @@ -612,5 +611,3 @@ def _get_parser_state(self, key: str, msg: str) -> str | None: ) class Triton(OxfordTriton): """Alias for backwards compatibility""" - - pass diff --git a/src/qcodes/instrument_drivers/rohde_schwarz/RTO1000.py b/src/qcodes/instrument_drivers/rohde_schwarz/RTO1000.py index 94ad53118d20..4ba31c6d8f99 100644 --- a/src/qcodes/instrument_drivers/rohde_schwarz/RTO1000.py +++ b/src/qcodes/instrument_drivers/rohde_schwarz/RTO1000.py @@ -1123,5 +1123,3 @@ class RTO1000(RohdeSchwarzRTO1000): """ Backwards compatibility alias for RohdeSchwarzRTO1000 """ - - pass diff --git a/src/qcodes/instrument_drivers/rohde_schwarz/Rohde_Schwarz_ZNB20.py b/src/qcodes/instrument_drivers/rohde_schwarz/Rohde_Schwarz_ZNB20.py index f4f95849bd95..1013bbcad3fe 100644 --- a/src/qcodes/instrument_drivers/rohde_schwarz/Rohde_Schwarz_ZNB20.py +++ b/src/qcodes/instrument_drivers/rohde_schwarz/Rohde_Schwarz_ZNB20.py @@ -6,5 +6,3 @@ class RohdeSchwarzZNB20(RohdeSchwarzZNBBase): QCoDeS driver for Rohde & Schwarz ZNB20 """ - - pass diff --git a/src/qcodes/instrument_drivers/rohde_schwarz/Rohde_Schwarz_ZNB8.py b/src/qcodes/instrument_drivers/rohde_schwarz/Rohde_Schwarz_ZNB8.py index 7eee00ba4fd2..c29aa0f8ff74 100644 --- a/src/qcodes/instrument_drivers/rohde_schwarz/Rohde_Schwarz_ZNB8.py +++ b/src/qcodes/instrument_drivers/rohde_schwarz/Rohde_Schwarz_ZNB8.py @@ -8,5 +8,3 @@ class RohdeSchwarzZNB8(RohdeSchwarzZNBBase): QCoDeS driver for Rohde & Schwarz ZNB8 """ - - pass diff --git a/src/qcodes/instrument_drivers/rohde_schwarz/ZNB.py b/src/qcodes/instrument_drivers/rohde_schwarz/ZNB.py index f8fad7c1f034..d485f54b3133 100644 --- a/src/qcodes/instrument_drivers/rohde_schwarz/ZNB.py +++ b/src/qcodes/instrument_drivers/rohde_schwarz/ZNB.py @@ -882,7 +882,7 @@ def update_lin_traces(self) -> None: start = self.start() stop = self.stop() npts = self.npts() - for _, parameter in self.parameters.items(): + for parameter in self.parameters.values(): if isinstance( parameter, (FrequencySweep, FrequencySweepMagPhase, FrequencySweepDBPhase), @@ -898,7 +898,7 @@ def update_cw_traces(self) -> None: """ bandwidth = self.bandwidth() npts = self.npts() - for _, parameter in self.parameters.items(): + for parameter in self.parameters.values(): if isinstance(parameter, FixedFrequencyTraceIQ): try: parameter.set_cw_sweep(npts, bandwidth) diff --git a/src/qcodes/instrument_drivers/rohde_schwarz/_rohde_schwarz_znle.py b/src/qcodes/instrument_drivers/rohde_schwarz/_rohde_schwarz_znle.py index 6846d86a6bcf..0fc41cd21230 100644 --- a/src/qcodes/instrument_drivers/rohde_schwarz/_rohde_schwarz_znle.py +++ b/src/qcodes/instrument_drivers/rohde_schwarz/_rohde_schwarz_znle.py @@ -7,8 +7,6 @@ class RohdeSchwarzZNLE3(RohdeSchwarzZNBBase): """ - pass - class RohdeSchwarzZNLE4(RohdeSchwarzZNBBase): """ @@ -16,8 +14,6 @@ class RohdeSchwarzZNLE4(RohdeSchwarzZNBBase): """ - pass - class RohdeSchwarzZNLE6(RohdeSchwarzZNBBase): """ @@ -25,8 +21,6 @@ class RohdeSchwarzZNLE6(RohdeSchwarzZNBBase): """ - pass - class RohdeSchwarzZNLE14(RohdeSchwarzZNBBase): """ @@ -34,13 +28,9 @@ class RohdeSchwarzZNLE14(RohdeSchwarzZNBBase): """ - pass - class RohdeSchwarzZNLE18(RohdeSchwarzZNBBase): """ QCoDeS driver for Rohde & Schwarz ZNLE18 """ - - pass diff --git a/src/qcodes/instrument_drivers/stanford_research/SG384.py b/src/qcodes/instrument_drivers/stanford_research/SG384.py index 7c1b58f2d6b4..66fd248b5edd 100644 --- a/src/qcodes/instrument_drivers/stanford_research/SG384.py +++ b/src/qcodes/instrument_drivers/stanford_research/SG384.py @@ -238,5 +238,3 @@ class SRS_SG384(SG384): """ Deprecated alternative name for backwards compatibility """ - - pass diff --git a/src/qcodes/instrument_drivers/stanford_research/SR86x.py b/src/qcodes/instrument_drivers/stanford_research/SR86x.py index a206d0f5da9c..da9824dcf62c 100644 --- a/src/qcodes/instrument_drivers/stanford_research/SR86x.py +++ b/src/qcodes/instrument_drivers/stanford_research/SR86x.py @@ -1292,7 +1292,7 @@ def get_data_channels_parameters( method_name = "get_latest" return tuple( - getattr(getattr(self.data_channels[i], "assigned_parameter"), method_name)() + getattr(self.data_channels[i].assigned_parameter, method_name)() for i in range(self._N_DATA_CHANNELS) ) diff --git a/src/qcodes/instrument_drivers/tektronix/AWG5014.py b/src/qcodes/instrument_drivers/tektronix/AWG5014.py index 5907bff2730b..c34364f346ca 100644 --- a/src/qcodes/instrument_drivers/tektronix/AWG5014.py +++ b/src/qcodes/instrument_drivers/tektronix/AWG5014.py @@ -1264,12 +1264,11 @@ def _generate_awg_file( log.warning(f"AWG: {k} not recognized as valid AWG channel setting") # waveforms - ii = 21 wf_record_str = BytesIO() wlist = list(packed_waveforms.keys()) wlist.sort() - for wf in wlist: + for ii, wf in enumerate(wlist, start=21): wfdat = packed_waveforms[wf] lenwfdat = len(wfdat) @@ -1282,13 +1281,11 @@ def _generate_awg_file( + self._pack_record(f"WAVEFORM_TIMESTAMP_{ii}", timetuple[:-1], "8H") + self._pack_record(f"WAVEFORM_DATA_{ii}", wfdat, f"{lenwfdat}H") ) - ii += 1 # sequence - kk = 1 seq_record_str = BytesIO() - for segment in wfname_l.transpose(): + for kk, segment in enumerate(wfname_l.transpose(), start=1): seq_record_str.write( self._pack_record(f"SEQUENCE_WAIT_{kk}", trig_wait[kk - 1], "h") + self._pack_record(f"SEQUENCE_LOOP_{kk}", int(nrep[kk - 1]), "l") @@ -1307,7 +1304,6 @@ def _generate_awg_file( "{}s".format(len(wfname + "\x00")), ) ) - kk += 1 awg_file = ( head_str.getvalue() @@ -1892,5 +1888,3 @@ class Tektronix_AWG5014(TektronixAWG5014): """ Alias with non-conformant name left for backwards compatibility """ - - pass diff --git a/src/qcodes/instrument_drivers/tektronix/AWG5208.py b/src/qcodes/instrument_drivers/tektronix/AWG5208.py index 0e7dc5c2cf0d..d87d477cbfa2 100644 --- a/src/qcodes/instrument_drivers/tektronix/AWG5208.py +++ b/src/qcodes/instrument_drivers/tektronix/AWG5208.py @@ -45,5 +45,3 @@ class AWG5208(TektronixAWG5208): """ Alias with non-conformant name left for backwards compatibility """ - - pass diff --git a/src/qcodes/instrument_drivers/tektronix/AWG70000A.py b/src/qcodes/instrument_drivers/tektronix/AWG70000A.py index 0f96df736929..9ae01df66a59 100644 --- a/src/qcodes/instrument_drivers/tektronix/AWG70000A.py +++ b/src/qcodes/instrument_drivers/tektronix/AWG70000A.py @@ -488,8 +488,6 @@ class AWGChannel(Tektronix70000AWGChannel): Alias for Tektronix70000AWGChannel for backwards compatibility. """ - pass - class TektronixAWG70000Base(VisaInstrument): """ diff --git a/src/qcodes/instrument_drivers/tektronix/AWG70002A.py b/src/qcodes/instrument_drivers/tektronix/AWG70002A.py index 1f1659902120..718622b3bcf7 100644 --- a/src/qcodes/instrument_drivers/tektronix/AWG70002A.py +++ b/src/qcodes/instrument_drivers/tektronix/AWG70002A.py @@ -48,5 +48,3 @@ class AWG70002A(TektronixAWG70002A): """ Alias with non-conformant name left for backwards compatibility """ - - pass diff --git a/src/qcodes/instrument_drivers/tektronix/AWGFileParser.py b/src/qcodes/instrument_drivers/tektronix/AWGFileParser.py index 567a7a29d6b8..f39e48b711af 100644 --- a/src/qcodes/instrument_drivers/tektronix/AWGFileParser.py +++ b/src/qcodes/instrument_drivers/tektronix/AWGFileParser.py @@ -335,7 +335,8 @@ def _unpacker( bitstring = bin(bitnum)[2:].zfill(16) m2[ii] = int(bitstring[0]) m1[ii] = int(bitstring[1]) - wf[ii] = (int(bitstring[2:], base=2) - 2**13) / 2**13 + wf[ii] = (int(bitstring[2:], base=2) - 2**13) / 2**13 # noqa: FURB166 + # the prefix of the bitsring is m2, m1 and not a int type prefix so disable FURB166 # print(bitstring, int(bitstring[2:], base=2)) return wf, m1, m2 diff --git a/src/qcodes/instrument_drivers/tektronix/DPO7200xx.py b/src/qcodes/instrument_drivers/tektronix/DPO7200xx.py index 3c546d2c0173..16b3fdd3be4e 100644 --- a/src/qcodes/instrument_drivers/tektronix/DPO7200xx.py +++ b/src/qcodes/instrument_drivers/tektronix/DPO7200xx.py @@ -51,8 +51,6 @@ class TektronixDPOModeError(Exception): perform an action """ - pass - @deprecated( "ModeError is deprecated. Please use qcodes.instrument_drivers.tektronix.TektronixDPOModeError instead.", @@ -64,8 +62,6 @@ class ModeError(TektronixDPOModeError): Alias for backwards compatibility """ - pass - class TektronixDPO7000xx(VisaInstrument): """ @@ -929,7 +925,7 @@ def __init__( f"CH{i}" for i in range(1, TektronixDPO7000xx.number_of_channels) ] - trigger_sources.extend([f"D{i}" for i in range(0, 16)]) + trigger_sources.extend([f"D{i}" for i in range(16)]) if self._identifier == "A": trigger_sources.append("line") diff --git a/src/qcodes/instrument_drivers/tektronix/Keithley_2000.py b/src/qcodes/instrument_drivers/tektronix/Keithley_2000.py index 90c7a35ad1d3..4af1e3d44aee 100644 --- a/src/qcodes/instrument_drivers/tektronix/Keithley_2000.py +++ b/src/qcodes/instrument_drivers/tektronix/Keithley_2000.py @@ -25,5 +25,3 @@ class Keithley_2000(Keithley2000): """ Backwards compatibility alias for Keithley 2000 driver """ - - pass diff --git a/src/qcodes/instrument_drivers/tektronix/Keithley_2400.py b/src/qcodes/instrument_drivers/tektronix/Keithley_2400.py index dbb1e971bf40..e6e9f12d0ad6 100644 --- a/src/qcodes/instrument_drivers/tektronix/Keithley_2400.py +++ b/src/qcodes/instrument_drivers/tektronix/Keithley_2400.py @@ -18,5 +18,3 @@ class Keithley_2400(Keithley2400): """ Backwards compatibility alias for Keithley 2400 driver """ - - pass diff --git a/src/qcodes/instrument_drivers/tektronix/Keithley_2600_channels.py b/src/qcodes/instrument_drivers/tektronix/Keithley_2600_channels.py index eed4a33d8570..ceb8e9c43311 100644 --- a/src/qcodes/instrument_drivers/tektronix/Keithley_2600_channels.py +++ b/src/qcodes/instrument_drivers/tektronix/Keithley_2600_channels.py @@ -37,5 +37,3 @@ class Keithley_2600(Keithley2600): """ Alias left for backwards compatibility. Will eventually be deprecated and removed. """ - - pass diff --git a/src/qcodes/instrument_drivers/tektronix/Keithley_3706A.py b/src/qcodes/instrument_drivers/tektronix/Keithley_3706A.py index c27c19bfbfdc..897a3329110c 100644 --- a/src/qcodes/instrument_drivers/tektronix/Keithley_3706A.py +++ b/src/qcodes/instrument_drivers/tektronix/Keithley_3706A.py @@ -27,5 +27,3 @@ class Keithley_3706A(Keithley3706A): """ Alias left for backwards compatibility. Will eventually be deprecated and removed. """ - - pass diff --git a/src/qcodes/instrument_drivers/tektronix/Keithley_6500.py b/src/qcodes/instrument_drivers/tektronix/Keithley_6500.py index 51a3a7cadba8..9cb67dbd8b8e 100644 --- a/src/qcodes/instrument_drivers/tektronix/Keithley_6500.py +++ b/src/qcodes/instrument_drivers/tektronix/Keithley_6500.py @@ -25,5 +25,3 @@ class Keithley_6500(Keithley6500): """ Alias left for backwards compatibility. Will eventually be deprecated and removed. """ - - pass diff --git a/src/qcodes/instrument_drivers/tektronix/TPS2012.py b/src/qcodes/instrument_drivers/tektronix/TPS2012.py index 3b373dc3d1d6..b82cf402614a 100644 --- a/src/qcodes/instrument_drivers/tektronix/TPS2012.py +++ b/src/qcodes/instrument_drivers/tektronix/TPS2012.py @@ -473,5 +473,3 @@ class TPS2012(TektronixTPS2012): """ Deprecated alias for ``TektronixTPS2012`` """ - - pass diff --git a/src/qcodes/interactive_widget.py b/src/qcodes/interactive_widget.py index 523dfa18015b..b1d085be482c 100644 --- a/src/qcodes/interactive_widget.py +++ b/src/qcodes/interactive_widget.py @@ -80,7 +80,7 @@ def on_click(_: Button) -> None: "Back", "warning", on_click=_back_button(title, body, box), - button_kwargs=dict(icon="undo"), + button_kwargs={"icon": "undo"}, ) box.children = (text_input, back_button) @@ -250,7 +250,7 @@ def _on_click(_: Button) -> None: f"Close {which}", "danger", on_click=delete_tab(out, tab), - button_kwargs=dict(icon="eraser"), + button_kwargs={"icon": "eraser"}, ) display(close_button) @@ -300,15 +300,15 @@ def on_click(_: Button) -> None: "", "success", on_click=_save_button(box, ds), - button_kwargs=dict(icon="save"), - layout_kwargs=dict(width="50%"), + button_kwargs={"icon": "save"}, + layout_kwargs={"width": "50%"}, ) cancel_button = button( "", "danger", on_click=_save_button(box, ds, do_save=False), - button_kwargs=dict(icon="close"), - layout_kwargs=dict(width="50%"), + button_kwargs={"icon": "close"}, + layout_kwargs={"width": "50%"}, ) subbox = HBox( [save_button, cancel_button], @@ -333,7 +333,7 @@ def _changeable_button(text: str, box: Box) -> Button: text, "success", on_click=_button_to_input(text, box), - button_kwargs=dict(icon="edit") if text == "" else {}, + button_kwargs={"icon": "edit"} if text == "" else {}, ) text = ds.metadata.get(_META_DATA_KEY, "") @@ -429,7 +429,7 @@ def _get_snapshot_button(ds: DataSetProtocol, tab: Tab) -> Button: "warning", tooltip="Click to open this DataSet's snapshot in a tab above.", on_click=_do_in_tab(tab, ds, "snapshot"), - button_kwargs=dict(icon="camera"), + button_kwargs={"icon": "camera"}, ) @@ -439,7 +439,7 @@ def _get_plot_button(ds: DataSetProtocol, tab: Tab) -> Button: "warning", tooltip="Click to open this DataSet's plot in a tab above.", on_click=_do_in_tab(tab, ds, "plot"), - button_kwargs=dict(icon="line-chart"), + button_kwargs={"icon": "line-chart"}, ) @@ -454,7 +454,7 @@ def _get_export_button( "csv", path=Path.cwd() / "export", ), - button_kwargs=dict(icon="file-export"), + button_kwargs={"icon": "file-export"}, ) diff --git a/src/qcodes/logger/logger.py b/src/qcodes/logger/logger.py index 96a48b2ec22d..97f3502f8a51 100644 --- a/src/qcodes/logger/logger.py +++ b/src/qcodes/logger/logger.py @@ -164,7 +164,7 @@ def generate_log_file_name() -> str: pid = str(os.getpid()) dt_str = datetime.now().strftime("%y%m%d") - python_log_name = "-".join([dt_str, pid, PYTHON_LOG_NAME]) + python_log_name = f"{dt_str}-{pid}-{PYTHON_LOG_NAME}" return python_log_name @@ -412,9 +412,11 @@ class LogCapture: def __init__( self, - logger: logging.Logger = logging.getLogger(), + logger: logging.Logger | None = None, level: LevelType | None = None, ) -> None: + if logger is None: + logger = logging.getLogger() self.logger = logger self.level = level or logging.NOTSET diff --git a/src/qcodes/math_utils/field_vector.py b/src/qcodes/math_utils/field_vector.py index 032c60c60f89..74efe14dbcea 100644 --- a/src/qcodes/math_utils/field_vector.py +++ b/src/qcodes/math_utils/field_vector.py @@ -205,7 +205,7 @@ def set_vector(self, **new_values: float) -> None: >>> f.set_vector(x=9, y=0, r=3) """ - names = sorted(list(new_values.keys())) + names = sorted(new_values.keys()) groups = [["x", "y", "z"], ["phi", "r", "theta"], ["phi", "rho", "z"]] if names not in groups: raise ValueError("Can only set vector with a complete value set") diff --git a/src/qcodes/parameters/cache.py b/src/qcodes/parameters/cache.py index 28c8f55ae6b4..59e71660282e 100644 --- a/src/qcodes/parameters/cache.py +++ b/src/qcodes/parameters/cache.py @@ -201,13 +201,8 @@ def _timestamp_expired(self) -> bool: oldest_accepted_timestamp = datetime.now() - timedelta( seconds=self._max_val_age ) - if self._timestamp < oldest_accepted_timestamp: - # Time of last get exceeds max_val_age seconds, need to - # perform new .get() - return True - else: - # parameter is still valid - return False + is_not_expired = self._timestamp < oldest_accepted_timestamp + return is_not_expired @overload def get(self, get_if_invalid: Literal[True]) -> ParameterDataTypeVar: ... diff --git a/src/qcodes/parameters/combined_parameter.py b/src/qcodes/parameters/combined_parameter.py index 44f70b13912e..f6777d487447 100644 --- a/src/qcodes/parameters/combined_parameter.py +++ b/src/qcodes/parameters/combined_parameter.py @@ -110,7 +110,7 @@ def __init__( if aggregator: self.f = aggregator - setattr(self, "aggregate", self._aggregate) + self.aggregate = self._aggregate def set(self, index: int) -> list[Any]: """ diff --git a/src/qcodes/parameters/delegate_parameter.py b/src/qcodes/parameters/delegate_parameter.py index 0a409a6335bf..d1b15ef7885e 100644 --- a/src/qcodes/parameters/delegate_parameter.py +++ b/src/qcodes/parameters/delegate_parameter.py @@ -176,7 +176,6 @@ def _update_with( delegate parameter mirrors the cache of the source parameter by design, this method is just a noop. """ - pass def __call__(self) -> _local_ParameterDataTypeVar: return self.get(get_if_invalid=True) diff --git a/src/qcodes/parameters/group_parameter.py b/src/qcodes/parameters/group_parameter.py index 894c0613f83b..6984b57df664 100644 --- a/src/qcodes/parameters/group_parameter.py +++ b/src/qcodes/parameters/group_parameter.py @@ -235,9 +235,8 @@ def __init__( for p in parameters: p._group = self - if single_instrument: - if len({p.root_instrument for p in parameters}) > 1: - raise ValueError("All parameters should belong to the same instrument") + if single_instrument and len({p.root_instrument for p in parameters}) > 1: + raise ValueError("All parameters should belong to the same instrument") self._instrument = parameters[0].root_instrument diff --git a/src/qcodes/parameters/parameter_base.py b/src/qcodes/parameters/parameter_base.py index 1b76f56fe38a..1984cbed6bcf 100644 --- a/src/qcodes/parameters/parameter_base.py +++ b/src/qcodes/parameters/parameter_base.py @@ -913,7 +913,7 @@ def get_wrapper(*args: Any, **kwargs: Any) -> ParameterDataTypeVar: except Exception as e: e.args = (*e.args, f"getting {self}") - raise e + raise return get_wrapper @@ -971,7 +971,7 @@ def set_wrapper(value: ParameterDataTypeVar, **kwargs: Any) -> None: except Exception as e: e.args = (*e.args, f"setting {self} to {value}") - raise e + raise return set_wrapper @@ -1377,7 +1377,7 @@ def _set_paramtype(self, paramtype: str) -> None: if self.vals is None: self.vals = new_vals elif type(self.vals) is not type(new_vals): - logging.warning( + LOG.warning( f"Tried to set a new paramtype {paramtype}, but this parameter already has paramtype {self.paramtype} which does not match" ) self.param_spec.type = paramtype diff --git a/src/qcodes/plotting/axis_labels.py b/src/qcodes/plotting/axis_labels.py index 2b8636552341..1bb4a4b06513 100644 --- a/src/qcodes/plotting/axis_labels.py +++ b/src/qcodes/plotting/axis_labels.py @@ -27,7 +27,6 @@ "ohm", "Ohm", "Ω", - "\N{GREEK CAPITAL LETTER OMEGA}", "S", "Wb", "T", diff --git a/src/qcodes/station.py b/src/qcodes/station.py index 1b604775f46d..d81b6d4da70a 100644 --- a/src/qcodes/station.py +++ b/src/qcodes/station.py @@ -97,8 +97,6 @@ def get_config_use_monitor() -> str | None: class ValidationWarning(Warning): """Replacement for jsonschema.error.ValidationError as warning.""" - pass - class StationConfig(dict[Any, Any]): def snapshot(self, update: bool = True) -> StationConfig: @@ -297,7 +295,7 @@ def remove_component(self, name: str) -> MetadatableWithName | None: if name in str(e): raise KeyError(f"Component {name} is not part of the station") else: - raise e + raise def get_component(self, full_name: str) -> MetadatableWithName: """ @@ -438,7 +436,7 @@ def load_config_files(self, *filenames: str) -> None: if len(filenames) == 0: self.load_config_file() else: - paths = list() + paths = [] for filename in filenames: assert isinstance(filename, str) path = self._get_config_file_path(filename) @@ -851,9 +849,10 @@ def update_schema_file( json.dump(data, f, indent=4) additional_instrument_modules = additional_instrument_modules or [] - instrument_modules: set[ModuleType] = set( - [qcodes.instrument_drivers, *additional_instrument_modules] - ) + instrument_modules: set[ModuleType] = { + qcodes.instrument_drivers, + *additional_instrument_modules, + } instrument_names = tuple( itertools.chain.from_iterable( diff --git a/src/qcodes/utils/attribute_helpers.py b/src/qcodes/utils/attribute_helpers.py index b2b32a27fc3a..801f93a5681e 100644 --- a/src/qcodes/utils/attribute_helpers.py +++ b/src/qcodes/utils/attribute_helpers.py @@ -98,7 +98,7 @@ def strip_attrs(obj: object, whitelist: "Sequence[str]" = ()) -> None: """ try: - lst = set(list(obj.__dict__.keys())) - set(whitelist) + lst = set(obj.__dict__.keys()) - set(whitelist) for key in lst: try: del obj.__dict__[key] diff --git a/src/qcodes/utils/delaykeyboardinterrupt.py b/src/qcodes/utils/delaykeyboardinterrupt.py index faa2bd5993ec..c9e5520f71a8 100644 --- a/src/qcodes/utils/delaykeyboardinterrupt.py +++ b/src/qcodes/utils/delaykeyboardinterrupt.py @@ -93,6 +93,9 @@ def __exit__( ) -> None: if self.old_handler is not None: signal.signal(signal.SIGINT, self.old_handler) - if self.signal_received is not None: - if self.old_handler is not None and not isinstance(self.old_handler, int): - self.old_handler(*self.signal_received) + if ( + self.signal_received is not None + and self.old_handler is not None + and not isinstance(self.old_handler, int) + ): + self.old_handler(*self.signal_received) diff --git a/src/qcodes/utils/function_helpers.py b/src/qcodes/utils/function_helpers.py index 4d79cf0a1ed8..d141860af82a 100644 --- a/src/qcodes/utils/function_helpers.py +++ b/src/qcodes/utils/function_helpers.py @@ -21,9 +21,8 @@ def is_function(f: object, arg_count: int, coroutine: bool | None = False) -> bo if not callable(f): return False - if coroutine is not None: - if bool(coroutine) is not iscoroutinefunction(f): - return False + if coroutine is not None and bool(coroutine) is not iscoroutinefunction(f): + return False if isinstance(f, type): # for type casting functions, eg int, str, float diff --git a/src/qcodes/utils/installation_info.py b/src/qcodes/utils/installation_info.py index 73837e1c52c2..2683f7b37b25 100644 --- a/src/qcodes/utils/installation_info.py +++ b/src/qcodes/utils/installation_info.py @@ -28,7 +28,7 @@ def is_qcodes_installed_editably() -> bool | None: stdout=subprocess.PIPE, ) e_pkgs = json.loads(pipproc.stdout.decode("utf-8")) - answer = any([d["name"] == "qcodes" for d in e_pkgs]) + answer = any(d["name"] == "qcodes" for d in e_pkgs) except Exception as e: # we actually do want a catch-all here log.warning(f"{type(e)}: {e!s}") answer = None diff --git a/src/qcodes/utils/json_utils.py b/src/qcodes/utils/json_utils.py index 64afb2e80818..7cd07fe89030 100644 --- a/src/qcodes/utils/json_utils.py +++ b/src/qcodes/utils/json_utils.py @@ -61,7 +61,7 @@ def default(self, o: Any) -> Any: } elif hasattr(o, "_JSONEncoder"): # Use object's custom JSON encoder - jsosencode = getattr(o, "_JSONEncoder") + jsosencode = o._JSONEncoder return jsosencode() else: try: @@ -82,7 +82,7 @@ def default(self, o: Any) -> Any: ): return { "__class__": type(o).__name__, - "__args__": getattr(o, "__getnewargs__")(), + "__args__": o.__getnewargs__(), } else: # we cannot convert the object to JSON, just take a string diff --git a/src/qcodes/validators/validators.py b/src/qcodes/validators/validators.py index 37beb98fbf83..3bcd2bcf6368 100644 --- a/src/qcodes/validators/validators.py +++ b/src/qcodes/validators/validators.py @@ -1020,20 +1020,26 @@ def validate(self, value: npt.NDArray, context: str = "") -> None: ) # Only check if max is not inf as it can be expensive for large arrays - if self._max_value != (float("inf")) and self._max_value is not None: - if not (np.max(value) <= self._max_value): - raise ValueError( - f"{value!r} is invalid: all values must be between " - f"{self._min_value} and {self._max_value} inclusive; {context}" - ) + if ( + self._max_value != (float("inf")) + and self._max_value is not None + and not (np.max(value) <= self._max_value) + ): + raise ValueError( + f"{value!r} is invalid: all values must be between " + f"{self._min_value} and {self._max_value} inclusive; {context}" + ) # Only check if min is not -inf as it can be expensive for large arrays - if self._min_value != (-float("inf")) and self._min_value is not None: - if not (self._min_value <= np.min(value)): - raise ValueError( - f"{value!r} is invalid: all values must be between " - f"{self._min_value} and {self._max_value} inclusive; {context}" - ) + if ( + self._min_value != (-float("inf")) + and self._min_value is not None + and not (self._min_value <= np.min(value)) + ): + raise ValueError( + f"{value!r} is invalid: all values must be between " + f"{self._min_value} and {self._max_value} inclusive; {context}" + ) is_numeric = True @@ -1061,6 +1067,9 @@ def max_value(self) -> float | None: return float(self._max_value) if self._max_value is not None else None +_ANYTHING = Anything() + + class Lists(Validator[list[T]]): """ Validator for lists @@ -1070,7 +1079,7 @@ class Lists(Validator[list[T]]): """ - def __init__(self, elt_validator: Validator[T] = Anything()) -> None: + def __init__(self, elt_validator: Validator[T] = _ANYTHING) -> None: self._elt_validator = elt_validator self._valid_values = ([vval for vval in elt_validator._valid_values],) @@ -1117,7 +1126,7 @@ class Sequence(Validator[typing.Sequence[Any]]): def __init__( self, - elt_validator: Validator[Any] = Anything(), + elt_validator: Validator[Any] = _ANYTHING, length: int | None = None, require_sorted: bool = False, ) -> None: diff --git a/tests/conftest.py b/tests/conftest.py index eae647bbd852..1d4741a1dbb8 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -38,7 +38,7 @@ def pytest_configure(config: pytest.Config) -> None: def pytest_runtest_setup(item: pytest.Item) -> None: - ALL = set("darwin linux win32".split()) + ALL = {"darwin", "linux", "win32"} supported_platforms = ALL.intersection(mark.name for mark in item.iter_markers()) if supported_platforms and sys.platform not in supported_platforms: pytest.skip(f"cannot run on platform {sys.platform}") diff --git a/tests/dataset/dond/test_dond_keyboard_interrupts.py b/tests/dataset/dond/test_dond_keyboard_interrupts.py index b236633d275b..91d59af1fb99 100644 --- a/tests/dataset/dond/test_dond_keyboard_interrupts.py +++ b/tests/dataset/dond/test_dond_keyboard_interrupts.py @@ -9,9 +9,8 @@ def test_catch_interrupts(): assert get_interrupt() is None # Test KeyboardInterrupt - with pytest.raises(KeyboardInterrupt): - with catch_interrupts() as get_interrupt: - raise KeyboardInterrupt() + with pytest.raises(KeyboardInterrupt), catch_interrupts() as get_interrupt: + raise KeyboardInterrupt() # Test BreakConditionInterrupt with catch_interrupts() as get_interrupt: @@ -20,12 +19,11 @@ def test_catch_interrupts(): # Test that cleanup code runs for KeyboardInterrupt cleanup_ran = False - with pytest.raises(KeyboardInterrupt): - with catch_interrupts(): - try: - raise KeyboardInterrupt() - finally: - cleanup_ran = True + with pytest.raises(KeyboardInterrupt), catch_interrupts(): + try: + raise KeyboardInterrupt() + finally: + cleanup_ran = True assert cleanup_ran # Test that cleanup code runs for BreakConditionInterrupt @@ -82,7 +80,7 @@ def simulated_sweep(interrupt_at=None): results = [] with pytest.raises(KeyboardInterrupt): for value in simulated_sweep(interrupt_at=3): - results.append(value) + results.append(value) # noqa: PERF402 assert results == [0, 1, 2] # Test interruption in nested sweeps @@ -94,6 +92,6 @@ def simulated_sweep(interrupt_at=None): for inner_value in simulated_sweep( interrupt_at=2 if outer_value == 1 else None ): - inner_results.append(inner_value) + inner_results.append(inner_value) # noqa: PERF402 assert outer_results == [0, 1] assert inner_results == [0, 1, 2, 3, 4, 0, 1] diff --git a/tests/dataset/measurement/test_load_legacy_data.py b/tests/dataset/measurement/test_load_legacy_data.py index 40bdb7abea84..05b83dd3108f 100644 --- a/tests/dataset/measurement/test_load_legacy_data.py +++ b/tests/dataset/measurement/test_load_legacy_data.py @@ -34,7 +34,7 @@ def test_load_legacy_files_2d() -> None: snapshot_str = data.get_metadata("snapshot") assert isinstance(snapshot_str, str) snapshot = json.loads(snapshot_str) - assert sorted(list(snapshot.keys())) == [ + assert sorted(snapshot.keys()) == [ "__class__", "arrays", "formatter", @@ -72,7 +72,7 @@ def test_load_legacy_files_1d() -> None: snapshot_str = data.get_metadata("snapshot") assert isinstance(snapshot_str, str) snapshot = json.loads(snapshot_str) - assert sorted(list(snapshot.keys())) == [ + assert sorted(snapshot.keys()) == [ "__class__", "arrays", "formatter", @@ -110,7 +110,7 @@ def test_load_legacy_files_1d_pathlib_path() -> None: snapshot_str = data.get_metadata("snapshot") assert isinstance(snapshot_str, str) snapshot = json.loads(snapshot_str) - assert sorted(list(snapshot.keys())) == [ + assert sorted(snapshot.keys()) == [ "__class__", "arrays", "formatter", diff --git a/tests/dataset/measurement/test_measurement_context_manager.py b/tests/dataset/measurement/test_measurement_context_manager.py index 59c7378ad6aa..bec9425740ab 100644 --- a/tests/dataset/measurement/test_measurement_context_manager.py +++ b/tests/dataset/measurement/test_measurement_context_manager.py @@ -413,10 +413,7 @@ def test_setting_write_period(wp) -> None: def test_setting_write_period_from_config(wp) -> None: qc.config.dataset.write_period = wp - if isinstance(wp, str): - with pytest.raises(ValueError): - Measurement() - elif wp < 1e-3: + if isinstance(wp, str) or wp < 1e-3: with pytest.raises(ValueError): Measurement() else: @@ -579,13 +576,13 @@ def collect_values_larger_than_7(results, length, state): @retry_until_does_not_throw( exception_class_to_expect=AssertionError, delay=0.5, tries=20 ) - def assert_states_updated_from_callbacks() -> None: - assert values_larger_than_7 == values_larger_than_7__expected + def assert_states_updated_from_callbacks(values, current_num) -> None: + assert values_larger_than_7 == values assert list(all_results_dict.keys()) == [ - result_index for result_index in range(1, num + 1 + 1) + result_index for result_index in range(1, current_num + 1 + 1) ] - assert_states_updated_from_callbacks() + assert_states_updated_from_callbacks(values_larger_than_7__expected, num) # Ensure that after exiting the "run()" context, # all subscribers get unsubscribed from the dataset @@ -722,7 +719,7 @@ def test_datasaver_scalars( # so we add a bit more wait time here if the expected number # of points have not been written for _ in range(10): - if not datasaver.points_written == breakpoint + 1: + if datasaver.points_written != breakpoint + 1: sleep(write_period * 1.1) assert datasaver.points_written == breakpoint + 1 @@ -780,11 +777,13 @@ class SomeMeasurementException(Exception): dataset = None # `pytest.raises`` is used here instead of custom try-except for convenience - with pytest.raises(SomeMeasurementException, match="foo") as e: - with meas.run() as datasaver: - dataset = datasaver.dataset + with ( + pytest.raises(SomeMeasurementException, match="foo") as e, + meas.run() as datasaver, + ): + dataset = datasaver.dataset - raise SomeMeasurementException("foo") + raise SomeMeasurementException("foo") assert dataset is not None metadata = dataset.metadata assert "measurement_exception" in metadata @@ -1355,10 +1354,12 @@ def test_datasaver_parameter_with_setpoints_that_are_different_raises( assert dep_ps in meas._interdeps.dependencies[param_ps] - with meas.run() as datasaver: + with ( + meas.run() as datasaver, + pytest.raises(ValueError, match="Multiple distinct values found for"), + ): # This fails because a 2D PWS expects 2D setpoints parameter values (ie a grid) - with pytest.raises(ValueError, match="Multiple distinct values found for"): - datasaver.add_result((param, param.get()), (sp_param_1, sp_param_1.get())) + datasaver.add_result((param, param.get()), (sp_param_1, sp_param_1.get())) @pytest.mark.parametrize("bg_writing", [True, False]) @@ -1542,8 +1543,9 @@ def test_datasaver_parameter_with_setpoints_reg_but_missing_validator( param.setpoints = () - with meas.run(write_in_background=bg_writing) as datasaver: - with pytest.raises( + with ( + meas.run(write_in_background=bg_writing) as datasaver, + pytest.raises( ValueError, match=r"Shape of output is not" r" consistent with setpoints." @@ -1554,11 +1556,13 @@ def test_datasaver_parameter_with_setpoints_reg_but_missing_validator( r"shape \(\)', 'getting dummy_" r"channel_inst_ChanA_dummy_" r"parameter_with_setpoints", - ): - datasaver.add_result(*expand_setpoints_helper(param)) + ), + ): + datasaver.add_result(*expand_setpoints_helper(param)) - with meas.run(write_in_background=bg_writing) as datasaver: - with pytest.raises( + with ( + meas.run(write_in_background=bg_writing) as datasaver, + pytest.raises( ValueError, match=r"Shape of output is not" r" consistent with setpoints." @@ -1569,8 +1573,9 @@ def test_datasaver_parameter_with_setpoints_reg_but_missing_validator( r"shape \(\)', 'getting dummy_" r"channel_inst_ChanA_dummy_" r"parameter_with_setpoints", - ): - datasaver.add_result((param, param.get())) + ), + ): + datasaver.add_result((param, param.get())) @pytest.mark.parametrize("bg_writing", [True, False]) @@ -2169,13 +2174,13 @@ def test_datasaver_arrays_of_different_length(storage_type, Ns, bg_writing) -> N with meas.run(write_in_background=bg_writing) as datasaver: result_t = ("temperature", 70) - result_freqs = list( + result_freqs = [ (f"freqs{n}", np.linspace(0, 1, Ns[n])) for n in range(no_of_signals) - ) - result_sigs = list( + ] + result_sigs = [ (f"signal{n}", np.random.default_rng().standard_normal(Ns[n])) for n in range(no_of_signals) - ) + ] full_result: tuple[tuple[str, int | np.ndarray | str], ...] = tuple( result_freqs + result_sigs + [result_t] ) diff --git a/tests/dataset/test_data_set_cache.py b/tests/dataset/test_data_set_cache.py index 486fd1b8415b..06b606193c50 100644 --- a/tests/dataset/test_data_set_cache.py +++ b/tests/dataset/test_data_set_cache.py @@ -134,41 +134,43 @@ def test_cache_standalone( for param in meas_parameters2: meas2.register_parameter(param) - with meas1.run( - write_in_background=bg_writing, in_memory_cache=in_memory_cache - ) as datasaver1: - with meas2.run( + with ( + meas1.run( write_in_background=bg_writing, in_memory_cache=in_memory_cache - ) as datasaver2: - dataset1 = datasaver1.dataset - dataset2 = datasaver2.dataset - _assert_parameter_data_is_identical( - dataset1.get_parameter_data(), dataset1.cache.data() - ) - _assert_parameter_data_is_identical( - dataset2.get_parameter_data(), dataset2.cache.data() - ) - for _ in range(n_points): - meas_vals1 = [(param, param.get()) for param in meas_parameters1] + ) as datasaver1, + meas2.run( + write_in_background=bg_writing, in_memory_cache=in_memory_cache + ) as datasaver2, + ): + dataset1 = datasaver1.dataset + dataset2 = datasaver2.dataset + _assert_parameter_data_is_identical( + dataset1.get_parameter_data(), dataset1.cache.data() + ) + _assert_parameter_data_is_identical( + dataset2.get_parameter_data(), dataset2.cache.data() + ) + for _ in range(n_points): + meas_vals1 = [(param, param.get()) for param in meas_parameters1] - datasaver1.add_result(*meas_vals1) - datasaver1.flush_data_to_database(block=True) + datasaver1.add_result(*meas_vals1) + datasaver1.flush_data_to_database(block=True) - meas_vals2 = [(param, param.get()) for param in meas_parameters2] + meas_vals2 = [(param, param.get()) for param in meas_parameters2] - datasaver2.add_result(*meas_vals2) - datasaver2.flush_data_to_database(block=True) + datasaver2.add_result(*meas_vals2) + datasaver2.flush_data_to_database(block=True) - _assert_parameter_data_is_identical( - dataset1.get_parameter_data(), - dataset1.cache.data(), - shaped_partial=set_shape, - ) - _assert_parameter_data_is_identical( - dataset2.get_parameter_data(), - dataset2.cache.data(), - shaped_partial=set_shape, - ) + _assert_parameter_data_is_identical( + dataset1.get_parameter_data(), + dataset1.cache.data(), + shaped_partial=set_shape, + ) + _assert_parameter_data_is_identical( + dataset2.get_parameter_data(), + dataset2.cache.data(), + shaped_partial=set_shape, + ) _assert_parameter_data_is_identical( dataset1.get_parameter_data(), dataset1.cache.data() ) @@ -316,43 +318,45 @@ def test_cache_1d( for param in meas_parameters2: meas2.register_parameter(param, setpoints=(setpoints_param,)) - with meas1.run( - write_in_background=bg_writing, in_memory_cache=in_memory_cache - ) as datasaver1: - with meas2.run( + with ( + meas1.run( write_in_background=bg_writing, in_memory_cache=in_memory_cache - ) as datasaver2: - dataset1 = datasaver1.dataset - dataset2 = datasaver2.dataset - _assert_parameter_data_is_identical( - dataset1.get_parameter_data(), dataset1.cache.data() - ) - _assert_parameter_data_is_identical( - dataset2.get_parameter_data(), dataset2.cache.data() - ) - for v in setpoints_values: - setpoints_param.set(v) + ) as datasaver1, + meas2.run( + write_in_background=bg_writing, in_memory_cache=in_memory_cache + ) as datasaver2, + ): + dataset1 = datasaver1.dataset + dataset2 = datasaver2.dataset + _assert_parameter_data_is_identical( + dataset1.get_parameter_data(), dataset1.cache.data() + ) + _assert_parameter_data_is_identical( + dataset2.get_parameter_data(), dataset2.cache.data() + ) + for v in setpoints_values: + setpoints_param.set(v) - meas_vals1 = [(param, param.get()) for param in meas_parameters1] + meas_vals1 = [(param, param.get()) for param in meas_parameters1] - datasaver1.add_result((setpoints_param, v), *meas_vals1) - datasaver1.flush_data_to_database(block=True) + datasaver1.add_result((setpoints_param, v), *meas_vals1) + datasaver1.flush_data_to_database(block=True) - meas_vals2 = [(param, param.get()) for param in meas_parameters2] + meas_vals2 = [(param, param.get()) for param in meas_parameters2] - datasaver2.add_result((setpoints_param, v), *meas_vals2) - datasaver2.flush_data_to_database(block=True) + datasaver2.add_result((setpoints_param, v), *meas_vals2) + datasaver2.flush_data_to_database(block=True) - _assert_parameter_data_is_identical( - dataset1.get_parameter_data(), - dataset1.cache.data(), - shaped_partial=set_shape, - ) - _assert_parameter_data_is_identical( - dataset2.get_parameter_data(), - dataset2.cache.data(), - shaped_partial=set_shape, - ) + _assert_parameter_data_is_identical( + dataset1.get_parameter_data(), + dataset1.cache.data(), + shaped_partial=set_shape, + ) + _assert_parameter_data_is_identical( + dataset2.get_parameter_data(), + dataset2.cache.data(), + shaped_partial=set_shape, + ) _assert_parameter_data_is_identical( dataset1.get_parameter_data(), dataset1.cache.data() ) diff --git a/tests/dataset/test_database_creation_and_upgrading.py b/tests/dataset/test_database_creation_and_upgrading.py index e8266b281413..b63f69ebf2df 100644 --- a/tests/dataset/test_database_creation_and_upgrading.py +++ b/tests/dataset/test_database_creation_and_upgrading.py @@ -246,10 +246,12 @@ def test_initialised_database_at_restores_db_location_on_error(tmp_path: Path) - db_location = str(tmp_path / "context_err.db") original_location = qc.config["core"]["db_location"] - with pytest.raises(RuntimeError, match="intentional"): - with initialised_database_at(db_location): - assert qc.config["core"]["db_location"] == db_location - raise RuntimeError("intentional") + with ( + pytest.raises(RuntimeError, match="intentional"), + initialised_database_at(db_location), + ): + assert qc.config["core"]["db_location"] == db_location + raise RuntimeError("intentional") assert qc.config["core"]["db_location"] == original_location diff --git a/tests/dataset/test_database_extract_runs.py b/tests/dataset/test_database_extract_runs.py index 7b0d727e8d49..a8952d4bf8ae 100644 --- a/tests/dataset/test_database_extract_runs.py +++ b/tests/dataset/test_database_extract_runs.py @@ -752,18 +752,17 @@ def test_old_versions_not_touched( # First test that we cannot use an old version as source - with raise_if_file_changed(fixturepath): - with pytest.warns(UserWarning) as warning: - extract_runs_into_db(fixturepath, target_path, 1) - expected_mssg = ( - "Source DB version is 2, but this " - f"function needs it to be in version {new_v}. " - "Run this function again with " - "upgrade_source_db=True to auto-upgrade " - "the source DB file." - ) - assert isinstance(warning[0].message, Warning) - assert warning[0].message.args[0] == expected_mssg + with raise_if_file_changed(fixturepath), pytest.warns(UserWarning) as warning: + extract_runs_into_db(fixturepath, target_path, 1) + expected_mssg = ( + "Source DB version is 2, but this " + f"function needs it to be in version {new_v}. " + "Run this function again with " + "upgrade_source_db=True to auto-upgrade " + "the source DB file." + ) + assert isinstance(warning[0].message, Warning) + assert warning[0].message.args[0] == expected_mssg # Then test that we cannot use an old version as target @@ -777,18 +776,17 @@ def test_old_versions_not_touched( source_ds.add_results([{name: 0.0 for name in some_interdeps[1].names}]) source_ds.mark_completed() - with raise_if_file_changed(fixturepath): - with pytest.warns(UserWarning) as warning: - extract_runs_into_db(source_path, fixturepath, 1) - expected_mssg = ( - "Target DB version is 2, but this " - f"function needs it to be in version {new_v}. " - "Run this function again with " - "upgrade_target_db=True to auto-upgrade " - "the target DB file." - ) - assert isinstance(warning[0].message, Warning) - assert warning[0].message.args[0] == expected_mssg + with raise_if_file_changed(fixturepath), pytest.warns(UserWarning) as warning: + extract_runs_into_db(source_path, fixturepath, 1) + expected_mssg = ( + "Target DB version is 2, but this " + f"function needs it to be in version {new_v}. " + "Run this function again with " + "upgrade_target_db=True to auto-upgrade " + "the target DB file." + ) + assert isinstance(warning[0].message, Warning) + assert warning[0].message.args[0] == expected_mssg def test_experiments_with_NULL_sample_name( @@ -909,11 +907,10 @@ def test_atomicity(two_empty_temp_db_connections, some_interdeps) -> None: source_ds_1.mark_completed() # now check that the target file is untouched - with raise_if_file_changed(target_path): + with raise_if_file_changed(target_path), pytest.raises(RuntimeError): # although the not completed error is a ValueError, we get the # RuntimeError from SQLite - with pytest.raises(RuntimeError): - extract_runs_into_db(source_path, target_path, 1, 2) + extract_runs_into_db(source_path, target_path, 1, 2) def test_column_mismatch(two_empty_temp_db_connections, some_interdeps, inst) -> None: diff --git a/tests/dataset/test_dataset_basic.py b/tests/dataset/test_dataset_basic.py index e0e45bb3b73d..d0ab9cf21ebb 100644 --- a/tests/dataset/test_dataset_basic.py +++ b/tests/dataset/test_dataset_basic.py @@ -420,7 +420,7 @@ def test_set_interdependencies(dataset) -> None: paramspecs = shadow_ds.paramspecs expected_keys = ["a_param", "b_param", "c_param"] - keys = sorted(list(paramspecs.keys())) + keys = sorted(paramspecs.keys()) assert keys == expected_keys for expected_param_name in expected_keys: ps = paramspecs[expected_param_name] diff --git a/tests/dataset/test_dataset_export.py b/tests/dataset/test_dataset_export.py index 4dd8f5ec4e11..a1fb18348f0b 100644 --- a/tests/dataset/test_dataset_export.py +++ b/tests/dataset/test_dataset_export.py @@ -846,7 +846,7 @@ def test_partally_overlapping_setpoint_xarray_export_two_params_partial( expected_size = (5, 4) # Each variable should be 2D and have matching coords - for _, da in xrds.data_vars.items(): + for da in xrds.data_vars.values(): assert len(da.dims) == 2 for dim, size in zip(da.dims, expected_size): assert dim in xrds.coords diff --git a/tests/dataset/test_dataset_in_memory.py b/tests/dataset/test_dataset_in_memory.py index 46825eca5704..f5e24c8c31d6 100644 --- a/tests/dataset/test_dataset_in_memory.py +++ b/tests/dataset/test_dataset_in_memory.py @@ -178,19 +178,21 @@ def test_dataset_in_memory_reload_from_db_3d( def test_dataset_in_memory_without_cache_raises( meas_with_registered_param, DMM, DAC, tmp_path ) -> None: - with pytest.raises( - RuntimeError, - match=re.escape( - "Cannot disable the in memory cache for a dataset that is only in memory." + with ( + pytest.raises( + RuntimeError, + match=re.escape( + "Cannot disable the in memory cache for a dataset that is only in memory." + ), ), - ): - with meas_with_registered_param.run( + meas_with_registered_param.run( dataset_class=DataSetType.DataSetInMem, in_memory_cache=False - ) as datasaver: - for set_v in np.linspace(0, 25, 10): - DAC.ch1.set(set_v) - get_v = DMM.v1() - datasaver.add_result((DAC.ch1, set_v), (DMM.v1, get_v)) + ) as datasaver, + ): + for set_v in np.linspace(0, 25, 10): + DAC.ch1.set(set_v) + get_v = DMM.v1() + datasaver.add_result((DAC.ch1, set_v), (DMM.v1, get_v)) def test_dataset_in_memory_reload_from_db_complex( diff --git a/tests/dataset/test_fix_functions.py b/tests/dataset/test_fix_functions.py index 80155811b298..bececdbe3e0d 100644 --- a/tests/dataset/test_fix_functions.py +++ b/tests/dataset/test_fix_functions.py @@ -55,9 +55,11 @@ def test_version_4a_bugfix_raises() -> None: skip_if_no_fixtures(dbname_old) - with temporarily_copied_DB(dbname_old, debug=False, version=3) as conn: - with pytest.raises(RuntimeError): - fix_version_4a_run_description_bug(conn) + with ( + temporarily_copied_DB(dbname_old, debug=False, version=3) as conn, + pytest.raises(RuntimeError), + ): + fix_version_4a_run_description_bug(conn) def test_fix_wrong_run_descriptions() -> None: @@ -107,6 +109,8 @@ def test_fix_wrong_run_descriptions_raises() -> None: skip_if_no_fixtures(dbname_old) - with temporarily_copied_DB(dbname_old, debug=False, version=4) as conn: - with pytest.raises(RuntimeError): - fix_wrong_run_descriptions(conn, [1]) + with ( + temporarily_copied_DB(dbname_old, debug=False, version=4) as conn, + pytest.raises(RuntimeError), + ): + fix_wrong_run_descriptions(conn, [1]) diff --git a/tests/dataset/test_guid_helpers.py b/tests/dataset/test_guid_helpers.py index 4c4c00674750..038631fc281e 100644 --- a/tests/dataset/test_guid_helpers.py +++ b/tests/dataset/test_guid_helpers.py @@ -63,11 +63,11 @@ def test_guids_from_list_str() -> None: "07fd7195-c51e-44d6-a085-fa8274cf00d6", "070d7195-c51e-44d6-a085-fa8274cf00d6", ] - assert guids_from_list_str("") == tuple() - assert guids_from_list_str("''") == tuple() - assert guids_from_list_str('""') == tuple() - assert guids_from_list_str(str(tuple())) == tuple() - assert guids_from_list_str(str(list())) == tuple() + assert guids_from_list_str("") == () + assert guids_from_list_str("''") == () + assert guids_from_list_str('""') == () + assert guids_from_list_str(str(())) == () + assert guids_from_list_str(str([])) == () assert guids_from_list_str(str({})) is None assert guids_from_list_str(str(guids)) == tuple(guids) assert guids_from_list_str(str([guids[0]])) == (guids[0],) @@ -75,7 +75,7 @@ def test_guids_from_list_str() -> None: assert guids_from_list_str(str(tuple(guids))) == tuple(guids) extracted_guids = guids_from_list_str(str(set(guids))) assert extracted_guids is not None - assert sorted(extracted_guids) == sorted(tuple(guids)) + assert sorted(extracted_guids) == sorted(guids) def test_many_guids_from_list_str() -> None: diff --git a/tests/dataset/test_measurement_extensions.py b/tests/dataset/test_measurement_extensions.py index 6531131ae48f..56fb450cc392 100644 --- a/tests/dataset/test_measurement_extensions.py +++ b/tests/dataset/test_measurement_extensions.py @@ -325,17 +325,19 @@ def test_dond_into_fails_with_together_sweeps( core_test_measurement = Measurement(name="core_test_1", exp=experiment) core_test_measurement.register_parameter(set1) core_test_measurement.register_parameter(meas1, setpoints=[set1]) - with pytest.raises(ValueError, match="dond_into does not support TogetherSweeps"): - with core_test_measurement.run() as datasaver: - sweep1 = LinSweep(set1, 0, 5, 11, 0.001) - sweep2 = LinSweep(set2, 10, 20, 11, 0.001) + with ( + pytest.raises(ValueError, match="dond_into does not support TogetherSweeps"), + core_test_measurement.run() as datasaver, + ): + sweep1 = LinSweep(set1, 0, 5, 11, 0.001) + sweep2 = LinSweep(set2, 10, 20, 11, 0.001) - dond_into( - datasaver, - TogetherSweep(sweep1, sweep2), # pyright: ignore [reportArgumentType] - meas1, - ) - _ = datasaver.dataset + dond_into( + datasaver, + TogetherSweep(sweep1, sweep2), # pyright: ignore [reportArgumentType] + meas1, + ) + _ = datasaver.dataset def test_dond_into_fails_with_groups(default_params, default_database_and_experiment): @@ -345,18 +347,18 @@ def test_dond_into_fails_with_groups(default_params, default_database_and_experi core_test_measurement = Measurement(name="core_test_1", exp=experiment) core_test_measurement.register_parameter(set1) core_test_measurement.register_parameter(meas1, setpoints=[set1]) - with pytest.raises( - ValueError, match="dond_into does not support multiple datasets" + with ( + pytest.raises(ValueError, match="dond_into does not support multiple datasets"), + core_test_measurement.run() as datasaver, ): - with core_test_measurement.run() as datasaver: - sweep1 = LinSweep(set1, 0, 5, 11, 0.001) - dond_into( - datasaver, - sweep1, - [meas1], # pyright: ignore [reportArgumentType] - [meas2], # pyright: ignore [reportArgumentType] - ) - _ = datasaver.dataset + sweep1 = LinSweep(set1, 0, 5, 11, 0.001) + dond_into( + datasaver, + sweep1, + [meas1], # pyright: ignore [reportArgumentType] + [meas2], # pyright: ignore [reportArgumentType] + ) + _ = datasaver.dataset def test_context_with_multiple_experiments( diff --git a/tests/dataset/test_plotting.py b/tests/dataset/test_plotting.py index 94d9e0dcec45..4834a0beefef 100644 --- a/tests/dataset/test_plotting.py +++ b/tests/dataset/test_plotting.py @@ -37,11 +37,9 @@ class TerminateLoopException(Exception): @given( param_name=text(min_size=1, max_size=10), param_label=text(min_size=0, max_size=15), - scale=sampled_from(sorted(list(_ENGINEERING_PREFIXES.keys()))), + scale=sampled_from(sorted(_ENGINEERING_PREFIXES.keys())), unit=sampled_from( - sorted( - list(_UNITS_FOR_RESCALING.union(["", "unit", "kg", "%", "permille", "nW"])) - ) + sorted(_UNITS_FOR_RESCALING.union(["", "unit", "kg", "%", "permille", "nW"])) ), data_strategy=data(), ) @@ -421,7 +419,7 @@ def test_plot_dataset_parameters(experiment, request: FixtureRequest, params) -> assert_allclose(np.array(plotted), data, rtol=1e-10) # check only 'requested' parameter has been plotted - elif params == "y" or "y2": + elif params in ["y", "y2"]: assert isinstance(params, str) assert len(axes) == 1 dsdata = dataset.get_parameter_data() diff --git a/tests/dataset/test_sqlite_base.py b/tests/dataset/test_sqlite_base.py index d55ec2f00f9c..d01b40f41861 100644 --- a/tests/dataset/test_sqlite_base.py +++ b/tests/dataset/test_sqlite_base.py @@ -167,9 +167,8 @@ def test_atomic_raises(experiment) -> None: bad_sql = '""' - with pytest.raises(RuntimeError) as excinfo: - with mut_conn.atomic(conn): - mut_conn.transaction(conn, bad_sql) + with pytest.raises(RuntimeError) as excinfo, mut_conn.atomic(conn): + mut_conn.transaction(conn, bad_sql) assert error_caused_by(excinfo, "syntax error") @@ -404,20 +403,22 @@ def just_throw(*args): # first we patch add_data_to_dynamic_columns to throw an exception # if create_data is not atomic this would create a partial # run in the db. Causing the next create_run to fail - with patch( - "qcodes.dataset.sqlite.queries.add_data_to_dynamic_columns", new=just_throw - ): - with pytest.raises( + with ( + patch( + "qcodes.dataset.sqlite.queries.add_data_to_dynamic_columns", new=just_throw + ), + pytest.raises( RuntimeError, match="Rolling back due to unhandled exception" - ) as e: - mut_queries.create_run( - experiment.conn, - experiment.exp_id, - name="testrun", - guid=generate_guid(), - description=simple_run_describer, - metadata={"a": 1}, - ) + ) as e, + ): + mut_queries.create_run( + experiment.conn, + experiment.exp_id, + name="testrun", + guid=generate_guid(), + description=simple_run_describer, + metadata={"a": 1}, + ) assert error_caused_by(e, "This breaks adding metadata") # since we are starting from an empty database and the above transaction # should be rolled back there should be no runs in the run table diff --git a/tests/dataset/test_sqlite_connection.py b/tests/dataset/test_sqlite_connection.py index 2b37da071500..62eb6e33b4b4 100644 --- a/tests/dataset/test_sqlite_connection.py +++ b/tests/dataset/test_sqlite_connection.py @@ -58,9 +58,8 @@ def test_atomic_raises_for_non_atomic_conn() -> None: "atomic context manager only accepts AtomicConnection " "database connection objects." ) - with pytest.raises(ValueError, match=match_str): - with atomic(sqlite_conn): # type: ignore[arg-type] - pass + with pytest.raises(ValueError, match=match_str), atomic(sqlite_conn): # type: ignore[arg-type] + pass def test_atomic() -> None: @@ -93,12 +92,14 @@ def test_atomic_with_exception() -> None: assert 25 == sqlite_conn.execute("PRAGMA user_version").fetchall()[0][0] - with pytest.raises( - RuntimeError, match="Rolling back due to unhandled exception" - ) as e: - with atomic(sqlite_conn) as atomic_conn: - atomic_conn.execute("PRAGMA user_version(42)") - raise Exception("intended exception") + with ( + pytest.raises( + RuntimeError, match="Rolling back due to unhandled exception" + ) as e, + atomic(sqlite_conn) as atomic_conn, + ): + atomic_conn.execute("PRAGMA user_version(42)") + raise Exception("intended exception") assert error_caused_by(e, "intended exception") assert 25 == sqlite_conn.execute("PRAGMA user_version").fetchall()[0][0] @@ -115,9 +116,8 @@ def test_atomic_on_outmost_connection_that_is_in_transaction() -> None: "Please commit those before starting an atomic " "transaction." ) - with pytest.raises(RuntimeError, match=match_str): - with atomic(conn): - pass + with pytest.raises(RuntimeError, match=match_str), atomic(conn): + pass @pytest.mark.parametrize("in_transaction", (True, False)) diff --git a/tests/delegate/test_delegate_instrument.py b/tests/delegate/test_delegate_instrument.py index aa6954a85512..7fab7fa389c3 100644 --- a/tests/delegate/test_delegate_instrument.py +++ b/tests/delegate/test_delegate_instrument.py @@ -28,7 +28,7 @@ def test_mock_field_delegate(station, field_x, chip_config) -> None: assert_almost_equal(ramp.field, 0.001) assert ramp.ramp_rate == 0.02 - field.ramp_X(dict(field=0.0, ramp_rate=10.0)) + field.ramp_X({"field": 0.0, "ramp_rate": 10.0}) assert field.ramp_rate() == 10.0 assert_almost_equal(field.X(), 0.0) assert field.ramp_X_ramp_rate() == 10.0 @@ -45,7 +45,7 @@ def test_delegate_channel_instrument(station, chip_config) -> None: assert state.bus == "off" assert state.gnd == "off" - switch.state01(dict(dac_output="on", smc="off", bus="off", gnd="off")) + switch.state01({"dac_output": "on", "smc": "off", "bus": "off", "gnd": "off"}) state = switch.state01() assert state.dac_output == "on" assert state.smc == "off" diff --git a/tests/drivers/AlazarTech/test_alazar_api.py b/tests/drivers/AlazarTech/test_alazar_api.py index cd4bbd70c794..7b778abbb557 100644 --- a/tests/drivers/AlazarTech/test_alazar_api.py +++ b/tests/drivers/AlazarTech/test_alazar_api.py @@ -129,7 +129,7 @@ def test_get_board_info(alazar_api) -> None: "board_kind", "max_samples", "bits_per_sample", - } == set(list(info.keys())) + } == set(info.keys()) assert info["system_id"] == SYSTEM_ID assert info["board_id"] == BOARD_ID @@ -151,7 +151,7 @@ def test_idn(alazar) -> None: "pcie_link_width", "bits_per_sample", "max_samples", - } == set(list(idn.keys())) + } == set(idn.keys()) assert idn["vendor"] == "AlazarTech" assert idn["model"][:3] == "ATS" diff --git a/tests/drivers/keysight_b1500/b1500_driver_tests/test_b1520a_cmu.py b/tests/drivers/keysight_b1500/b1500_driver_tests/test_b1520a_cmu.py index 4a5532f5d2c7..b7b54cef35d9 100644 --- a/tests/drivers/keysight_b1500/b1500_driver_tests/test_b1520a_cmu.py +++ b/tests/drivers/keysight_b1500/b1500_driver_tests/test_b1520a_cmu.py @@ -215,7 +215,7 @@ def test_cv_sweep_voltages(cmu: KeysightB1520A) -> None: cmu.cv_sweep.sweep_steps(steps) voltages = cmu.cv_sweep_voltages() - assert all([a == b for a, b in zip(np.linspace(start, end, steps), voltages)]) + assert all(a == b for a, b in zip(np.linspace(start, end, steps), voltages)) def test_sweep_modes(cmu: KeysightB1520A) -> None: @@ -234,7 +234,7 @@ def test_sweep_modes(cmu: KeysightB1520A) -> None: cmu.cv_sweep.sweep_mode(mode) voltages = cmu.cv_sweep_voltages() - assert all([a == b for a, b in zip((-1.0, 0.0, 1.0, 0.0, -1.0), voltages)]) + assert all(a == b for a, b in zip((-1.0, 0.0, 1.0, 0.0, -1.0), voltages)) def test_run_sweep(cmu: KeysightB1520A) -> None: diff --git a/tests/drivers/test_Keysight_33XXX.py b/tests/drivers/test_Keysight_33XXX.py index b575f19cc676..49a0e613cd73 100644 --- a/tests/drivers/test_Keysight_33XXX.py +++ b/tests/drivers/test_Keysight_33XXX.py @@ -96,11 +96,9 @@ def test_wrong_model_warns( assert len(warns) >= 4 assert ( sum( - [ - "The driver class name " in record.msg - and "does not match the detected model" in record.msg - for record in warns - ] + "The driver class name " in record.msg + and "does not match the detected model" in record.msg + for record in warns ) == 4 ) diff --git a/tests/drivers/test_ami430_visa.py b/tests/drivers/test_ami430_visa.py index b5bd21a623b2..864deaf00d9b 100644 --- a/tests/drivers/test_ami430_visa.py +++ b/tests/drivers/test_ami430_visa.py @@ -551,7 +551,7 @@ def test_field_limit_exception(current_driver) -> None: set_points = zip(*(i.flatten() for i in np.meshgrid(x, y, z))) for set_point in set_points: - should_not_raise = any([is_safe(*set_point) for is_safe in field_limit]) + should_not_raise = any(is_safe(*set_point) for is_safe in field_limit) if should_not_raise: current_driver.cartesian(set_point) @@ -561,7 +561,7 @@ def test_field_limit_exception(current_driver) -> None: assert "field would exceed limit" in excinfo.value.args[0] vals_and_setpoints = zip(current_driver.cartesian(), set_point) - belief = not (all([val == sp for val, sp in vals_and_setpoints])) + belief = not (all(val == sp for val, sp in vals_and_setpoints)) assert belief diff --git a/tests/drivers/test_cryomagnetics_4g.py b/tests/drivers/test_cryomagnetics_4g.py index ac9943cf6d48..23d0906669fa 100644 --- a/tests/drivers/test_cryomagnetics_4g.py +++ b/tests/drivers/test_cryomagnetics_4g.py @@ -95,16 +95,16 @@ def test_set_field_successful( ) -> None: with ( patch.object(cryo_instrument, "write") as mock_write, + caplog.at_level(logging.WARNING), ): - with caplog.at_level(logging.WARNING): - cryo_instrument.set_field(0.1, block=False) - calls = [ - call - for call in mock_write.call_args_list - if "LLIM" in call[0][0] or "SWEEP" in call[0][0] - ] - assert any("SWEEP UP" in str(call) for call in calls) - assert "Magnetic field is ramping but not currently blocked!" in caplog.text + cryo_instrument.set_field(0.1, block=False) + calls = [ + call + for call in mock_write.call_args_list + if "LLIM" in call[0][0] or "SWEEP" in call[0][0] + ] + assert any("SWEEP UP" in str(call) for call in calls) + assert "Magnetic field is ramping but not currently blocked!" in caplog.text def test_set_field_blocking(cryo_instrument: CryomagneticsModel4G) -> None: @@ -153,9 +153,9 @@ def mock_time() -> float: "qcodes.instrument_drivers.cryomagnetics._cryomagnetics4g._time", side_effect=mock_time, ), + pytest.raises(Cryomagnetics4GException, match=r"Timeout|stabilized"), ): - with pytest.raises(Cryomagnetics4GException, match=r"Timeout|stabilized"): - cryo_instrument.wait_while_ramping(1.0, threshold=1e-4) + cryo_instrument.wait_while_ramping(1.0, threshold=1e-4) def test_wait_while_ramping_success(cryo_instrument: CryomagneticsModel4G) -> None: diff --git a/tests/drivers/test_cryomagnetics_TM620.py b/tests/drivers/test_cryomagnetics_TM620.py index 294f69ba4568..5608e9b816a5 100644 --- a/tests/drivers/test_cryomagnetics_TM620.py +++ b/tests/drivers/test_cryomagnetics_TM620.py @@ -47,9 +47,11 @@ def test_parse_output_valid(tm620): def test_parse_output_invalid(tm620, caplog): - with caplog.at_level("ERROR"): - with pytest.raises(ValueError, match="No floating point number found"): - tm620._parse_output("Invalid output") + with ( + caplog.at_level("ERROR"), + pytest.raises(ValueError, match="No floating point number found"), + ): + tm620._parse_output("Invalid output") assert "No floating point number found in output" in caplog.text @@ -59,7 +61,6 @@ def test_convert_to_numerics_valid(tm620): def test_convert_to_numerics_invalid(tm620, caplog): - with caplog.at_level("ERROR"): - with pytest.raises(ValueError, match="Unable to convert"): - tm620._convert_to_numeric("not_a_number") + with caplog.at_level("ERROR"), pytest.raises(ValueError, match="Unable to convert"): + tm620._convert_to_numeric("not_a_number") assert "Error converting 'not_a_number' to float" in caplog.text diff --git a/tests/drivers/test_keithley_26xx.py b/tests/drivers/test_keithley_26xx.py index 5d935728af8a..a1043fba1069 100644 --- a/tests/drivers/test_keithley_26xx.py +++ b/tests/drivers/test_keithley_26xx.py @@ -22,7 +22,7 @@ def _make_driver(): @pytest.fixture(scope="function", name="smus") def _make_smus(driver): smu_names = {"smua", "smub"} - assert smu_names == set(list(driver.submodules.keys())) + assert smu_names == set(driver.submodules.keys()) yield tuple(getattr(driver, smu_name) for smu_name in smu_names) @@ -37,7 +37,7 @@ def test_idn(driver) -> None: def test_smu_channels_and_their_parameters(driver) -> None: - assert {"smua", "smub"} == set(list(driver.submodules.keys())) + assert {"smua", "smub"} == set(driver.submodules.keys()) for smu_name in ("smua", "smub"): smu = getattr(driver, smu_name) diff --git a/tests/drivers/test_keithley_s46.py b/tests/drivers/test_keithley_s46.py index 907e4cb1b788..41ac2a6313a4 100644 --- a/tests/drivers/test_keithley_s46.py +++ b/tests/drivers/test_keithley_s46.py @@ -23,7 +23,7 @@ def calc_channel_nr(alias: str) -> int: return offset_dict[alias[0]] + int(alias[1:]) assert all( - [nr == calc_channel_nr(al) for al, nr in KeithleyS46.channel_numbers.items()] + nr == calc_channel_nr(al) for al, nr in KeithleyS46.channel_numbers.items() ) diff --git a/tests/drivers/test_keysight_b220x.py b/tests/drivers/test_keysight_b220x.py index 9b0aa16a9bca..a1da461f276c 100644 --- a/tests/drivers/test_keysight_b220x.py +++ b/tests/drivers/test_keysight_b220x.py @@ -65,9 +65,9 @@ def test_connect_emits_warning_on_statusbyte_not_null(uut) -> None: with pytest.warns(UserWarning): uut.connect(12, 33) - # The simulated instrument does not reset the settings to default - # values, so gnd mode is explicitly disabled here: - uut.gnd_mode(False) + # The simulated instrument does not reset the settings to default + # values, so gnd mode is explicitly disabled here: + uut.gnd_mode(False) def test_disconnect_throws_at_invalid_channel_number(uut) -> None: diff --git a/tests/drivers/test_lakeshore_335.py b/tests/drivers/test_lakeshore_335.py index d676bd15efb1..0cb007dbd948 100644 --- a/tests/drivers/test_lakeshore_335.py +++ b/tests/drivers/test_lakeshore_335.py @@ -13,7 +13,7 @@ log = logging.getLogger(__name__) -VISA_LOGGER = ".".join((InstrumentBase.__module__, "com", "visa")) +VISA_LOGGER = f"{InstrumentBase.__module__}.com.visa" class LakeshoreModel335Mock(MockVisaInstrument, LakeshoreModel335): diff --git a/tests/drivers/test_lakeshore_336.py b/tests/drivers/test_lakeshore_336.py index e7923c1010b7..3056482c57b2 100644 --- a/tests/drivers/test_lakeshore_336.py +++ b/tests/drivers/test_lakeshore_336.py @@ -15,7 +15,7 @@ log = logging.getLogger(__name__) -VISA_LOGGER = ".".join((InstrumentBase.__module__, "com", "visa")) +VISA_LOGGER = f"{InstrumentBase.__module__}.com.visa" class LakeshoreModel336Mock(MockVisaInstrument, LakeshoreModel336): diff --git a/tests/drivers/test_lakeshore_372.py b/tests/drivers/test_lakeshore_372.py index e88dbbb95979..b6085bc3b5f9 100644 --- a/tests/drivers/test_lakeshore_372.py +++ b/tests/drivers/test_lakeshore_372.py @@ -22,7 +22,7 @@ log = logging.getLogger(__name__) -VISA_LOGGER = ".".join((InstrumentBase.__module__, "com", "visa")) +VISA_LOGGER = f"{InstrumentBase.__module__}.com.visa" P = ParamSpec("P") T = TypeVar("T") @@ -62,9 +62,9 @@ def __init__(self, *args, **kwargs) -> None: f = getattr(self, func_name) # only add for methods that have such an attribute with suppress(AttributeError): - self.queries[getattr(f, "query_name")] = f + self.queries[f.query_name] = f with suppress(AttributeError): - self.cmds[getattr(f, "command_name")] = f + self.cmds[f.command_name] = f def write_raw(self, cmd) -> None: cmd_parts = cmd.split(" ") diff --git a/tests/drivers/test_stahl.py b/tests/drivers/test_stahl.py index 6d31d7cc8525..3f43143adcdd 100644 --- a/tests/drivers/test_stahl.py +++ b/tests/drivers/test_stahl.py @@ -94,4 +94,3 @@ def test_get_temperature(stahl_instrument) -> None: Line 191 of pyvisa-sim/component.py should read "return response.encode('latin-1')" for this to work. """ - pass diff --git a/tests/drivers/test_tektronix_AWG70000A.py b/tests/drivers/test_tektronix_AWG70000A.py index 4c51c97071e0..c1ef9d98b5cf 100644 --- a/tests/drivers/test_tektronix_AWG70000A.py +++ b/tests/drivers/test_tektronix_AWG70000A.py @@ -25,7 +25,7 @@ def strip_outer_tags(sml: str) -> str: complies with the schema provided by tektronix """ # make function idempotent - if not sml[1:9] == "DataFile": + if sml[1:9] != "DataFile": print("Incorrect file format or outer tags already stripped") return sml diff --git a/tests/extensions/parameters/test_parameter_mixin.py b/tests/extensions/parameters/test_parameter_mixin.py index 8de743fe2d1c..adfcc22b2149 100644 --- a/tests/extensions/parameters/test_parameter_mixin.py +++ b/tests/extensions/parameters/test_parameter_mixin.py @@ -13,20 +13,14 @@ class CompatibleParameter(Parameter): """Docstring for CompatibleParameter""" - pass - class AnotherCompatibleParameter(Parameter): """Docstring for AnotherCompatibleParameter""" - pass - class IncompatibleParameter(Parameter): """Docstring for IncompatibleParameter""" - pass - class CompatibleParameterMixin(ParameterMixin): """Docstring for CompatibleParameterMixin""" diff --git a/tests/extensions/parameters/test_parameter_mixin_interdependent.py b/tests/extensions/parameters/test_parameter_mixin_interdependent.py index 889ecf520665..5c41392ab0ad 100644 --- a/tests/extensions/parameters/test_parameter_mixin_interdependent.py +++ b/tests/extensions/parameters/test_parameter_mixin_interdependent.py @@ -159,25 +159,26 @@ def test_error_on_non_interdependent_dependency(store, mock_instr) -> None: ) """A non-interdependent parameter.""" - with pytest.warns(QCoDeSDeprecationWarning, match="does not correctly pass kwargs"): - with pytest.raises( + with ( + pytest.warns(QCoDeSDeprecationWarning, match="does not correctly pass kwargs"), + pytest.raises( KeyError, match="Duplicate parameter name managed_param on instrument" - ): - with pytest.raises( - TypeError, match="must be an instance of InterdependentParameterMixin" - ): - mock_instr.managed_param = cast( - "InterdependentParameter", - mock_instr.add_parameter( - name="managed_param", - parameter_class=InterdependentParameter, - dependent_on=["not_interdependent_param"], - set_cmd=lambda x: store.update({"managed": x}), - get_cmd=lambda: store.get("managed"), - docstring="Parameter managed_param depends on a non-interdependent param.", - ), - ) - """Parameter managed_param depends on a non-interdependent param.""" + ), + pytest.raises( + TypeError, match="must be an instance of InterdependentParameterMixin" + ), + ): + mock_instr.managed_param = cast( + "InterdependentParameter", + mock_instr.add_parameter( + name="managed_param", + parameter_class=InterdependentParameter, + dependent_on=["not_interdependent_param"], + set_cmd=lambda x: store.update({"managed": x}), + get_cmd=lambda: store.get("managed"), + docstring="Parameter managed_param depends on a non-interdependent param.", + ), + ) def test_parsers_and_dependency_propagation(store, mock_instr) -> None: diff --git a/tests/extensions/parameters/test_parameter_mixin_on_cache_change.py b/tests/extensions/parameters/test_parameter_mixin_on_cache_change.py index 0ee917904631..dd5bed990144 100644 --- a/tests/extensions/parameters/test_parameter_mixin_on_cache_change.py +++ b/tests/extensions/parameters/test_parameter_mixin_on_cache_change.py @@ -21,8 +21,6 @@ class OnCacheChangeParameter(OnCacheChangeParameterMixin, Parameter): A parameter invoking callbacks on cache changes. """ - pass - @pytest.fixture def store(): diff --git a/tests/extensions/parameters/test_parameter_mixin_set_cache_value_on_reset.py b/tests/extensions/parameters/test_parameter_mixin_set_cache_value_on_reset.py index 7bc80a0177d7..69caa2270a89 100644 --- a/tests/extensions/parameters/test_parameter_mixin_set_cache_value_on_reset.py +++ b/tests/extensions/parameters/test_parameter_mixin_set_cache_value_on_reset.py @@ -27,8 +27,6 @@ class ResetTestParameter(SetCacheValueOnResetParameterMixin, Parameter): A parameter resetting its cache value on instrument reset. """ - pass - @pytest.fixture def store(): @@ -136,33 +134,37 @@ def test_direct_cache_update_and_reset(store, reset_instr) -> None: def test_error_if_get_cmd_supplied(reset_instr) -> None: - with pytest.warns(QCoDeSDeprecationWarning, match="does not correctly pass kwargs"): + with ( + pytest.warns(QCoDeSDeprecationWarning, match="does not correctly pass kwargs"), + pytest.raises(TypeError, match="without 'get_cmd'"), + ): # with pytest.raises(KeyError, match="Duplicate parameter name managed_param on instrument"): - with pytest.raises(TypeError, match="without 'get_cmd'"): - reset_instr.add_parameter( - name="test_param_error", - parameter_class=ResetTestParameter, - group_names=["reset_group_general"], - cache_value_after_reset=42, - set_cmd=lambda x: None, - get_cmd=lambda: 100, - docstring="A parameter incorrectly supplying get_cmd.", - ) + reset_instr.add_parameter( + name="test_param_error", + parameter_class=ResetTestParameter, + group_names=["reset_group_general"], + cache_value_after_reset=42, + set_cmd=lambda x: None, + get_cmd=lambda: 100, + docstring="A parameter incorrectly supplying get_cmd.", + ) def test_error_if_get_parser_supplied(reset_instr) -> None: - with pytest.warns(QCoDeSDeprecationWarning, match="does not correctly pass kwargs"): + with ( + pytest.warns(QCoDeSDeprecationWarning, match="does not correctly pass kwargs"), + pytest.raises(TypeError, match="Supplying 'get_parser' is not allowed"), + ): # with pytest.raises(KeyError, match="Duplicate parameter name managed_param on instrument"): - with pytest.raises(TypeError, match="Supplying 'get_parser' is not allowed"): - reset_instr.add_parameter( - name="test_param_get_parser_error", - parameter_class=ResetTestParameter, - group_names=["reset_group_general"], - cache_value_after_reset=42, - set_cmd=lambda x: None, - get_parser=lambda x: x + 1, - docstring="A parameter incorrectly supplying get_parser.", - ) + reset_instr.add_parameter( + name="test_param_get_parser_error", + parameter_class=ResetTestParameter, + group_names=["reset_group_general"], + cache_value_after_reset=42, + set_cmd=lambda x: None, + get_parser=lambda x: x + 1, + docstring="A parameter incorrectly supplying get_parser.", + ) def test_parameter_in_multiple_reset_groups(store, reset_instr) -> None: @@ -227,14 +229,14 @@ def test_warning_if_group_names_missing(store, reset_instr): def test_typeerror_if_group_names_invalid(store, reset_instr): - with pytest.warns(QCoDeSDeprecationWarning): - with pytest.raises( - TypeError, match="group_names must be a list of strings or None" - ): - reset_instr.add_parameter( - name="test_param", - parameter_class=ResetTestParameter, - cache_value_after_reset=42, - group_names=123, - set_cmd=lambda x: store.update({"reset_param": x}), - ) + with ( + pytest.warns(QCoDeSDeprecationWarning), + pytest.raises(TypeError, match="group_names must be a list of strings or None"), + ): + reset_instr.add_parameter( + name="test_param", + parameter_class=ResetTestParameter, + cache_value_after_reset=42, + group_names=123, + set_cmd=lambda x: store.update({"reset_param": x}), + ) diff --git a/tests/extensions/test_infer.py b/tests/extensions/test_infer.py index 087dd169de02..afcd12e4cba9 100644 --- a/tests/extensions/test_infer.py +++ b/tests/extensions/test_infer.py @@ -275,10 +275,10 @@ def test_parameters_on_delegate_instruments(instrument_fixture, good_inst_delega def test_merge_user_and_class_attrs(): InferAttrs.add("attr1") attr_set = _merge_user_and_class_attrs("attr2") - assert set(("attr1", "attr2")) == attr_set + assert {"attr1", "attr2"} == attr_set attr_set_list = _merge_user_and_class_attrs(("attr2", "attr3")) - assert set(("attr1", "attr2", "attr3")) == attr_set_list + assert {"attr1", "attr2", "attr3"} == attr_set_list def test_infer_attrs(): @@ -286,14 +286,14 @@ def test_infer_attrs(): assert InferAttrs.known_attrs() == () InferAttrs.add("attr1") - assert set(InferAttrs.known_attrs()) == set(("attr1",)) + assert set(InferAttrs.known_attrs()) == {"attr1"} InferAttrs.add("attr2") InferAttrs.discard("attr1") - assert set(InferAttrs.known_attrs()) == set(("attr2",)) + assert set(InferAttrs.known_attrs()) == {"attr2"} InferAttrs.add(("attr1", "attr3")) - assert set(InferAttrs.known_attrs()) == set(("attr1", "attr2", "attr3")) + assert set(InferAttrs.known_attrs()) == {"attr1", "attr2", "attr3"} def test_get_parameter_chain_with_loops(good_inst_delegates): @@ -327,7 +327,7 @@ def test_chain_links_of_type(): InferAttrs.add("linked_parameter") user_links = get_chain_links_of_type(UserLinkingParameter, user_link_2) - assert set(user_links) == set([user_link, user_link_2]) + assert set(user_links) == {user_link, user_link_2} def test_sole_chain_link_of_type(): @@ -362,7 +362,7 @@ def test_get_instrument_from_chain( instruments = get_parent_instruments_from_chain_of_type( DummyInstrument, good_inst_del_3 ) - assert set(instruments) == set([inst, inst2]) + assert set(instruments) == {inst, inst2} def test_get_sole_instrument_from_chain(instrument_fixture2, multi_inst_chain): diff --git a/tests/parameter/test_delegate_parameter.py b/tests/parameter/test_delegate_parameter.py index 83c00a18e825..9cd77200c87e 100644 --- a/tests/parameter/test_delegate_parameter.py +++ b/tests/parameter/test_delegate_parameter.py @@ -121,7 +121,7 @@ def test_same_label_and_unit_on_init(simple_param: Parameter) -> None: def test_overwritten_unit_on_init(simple_param: Parameter) -> None: d = DelegateParameter("test_delegate_parameter", source=simple_param, unit="Ohm") assert d.label == simple_param.label - assert not d.unit == simple_param.unit + assert d.unit != simple_param.unit assert d.unit == "Ohm" @@ -130,7 +130,7 @@ def test_overwritten_label_on_init(simple_param: Parameter) -> None: "test_delegate_parameter", source=simple_param, label="Physical parameter" ) assert d.unit == simple_param.unit - assert not d.label == simple_param.label + assert d.label != simple_param.label assert d.label == "Physical parameter" diff --git a/tests/parameter/test_on_off_mapping.py b/tests/parameter/test_on_off_mapping.py index 190ef33dde29..2bb4df4f8ede 100644 --- a/tests/parameter/test_on_off_mapping.py +++ b/tests/parameter/test_on_off_mapping.py @@ -7,7 +7,7 @@ def test_values_of_mapping_are_only_the_given_two() -> None: val_mapping = create_on_off_val_mapping(on_val="666", off_val="000") - values_set = set(list(val_mapping.values())) + values_set = set(val_mapping.values()) assert values_set == {"000", "666"} diff --git a/tests/parameter/test_parameter_context_manager.py b/tests/parameter/test_parameter_context_manager.py index 09171ad115ec..a735844e52d5 100644 --- a/tests/parameter/test_parameter_context_manager.py +++ b/tests/parameter/test_parameter_context_manager.py @@ -279,7 +279,6 @@ def test_reset_at_exit_with_allow_changes_false( ) -> None: p = instrument.a p.set(2) - with p.restore_at_exit(allow_changes=False): - with pytest.raises(TypeError): - p.set(5) + with p.restore_at_exit(allow_changes=False), pytest.raises(TypeError): + p.set(5) assert p() == 2 diff --git a/tests/parameter/test_permissive_range.py b/tests/parameter/test_permissive_range.py index 76160485502a..c0a5928a956f 100644 --- a/tests/parameter/test_permissive_range.py +++ b/tests/parameter/test_permissive_range.py @@ -24,7 +24,7 @@ @pytest.mark.parametrize("args", bad_args) def test_bad_calls(args) -> None: - with pytest.raises(Exception): + with pytest.raises(TypeError): permissive_range(*args) diff --git a/tests/parameter/test_snapshot.py b/tests/parameter/test_snapshot.py index 8cc09df3ff30..ba0acf9ab0b8 100644 --- a/tests/parameter/test_snapshot.py +++ b/tests/parameter/test_snapshot.py @@ -23,9 +23,12 @@ def create_parameter( get_cmd: Callable[..., Any] | bool | None | Literal["NOT_PASSED"], offset: float | Literal["NOT_PASSED"] = NOT_PASSED, ) -> Parameter: - kwargs: dict[str, Any] = dict( - set_cmd=None, label="Parameter", unit="a.u.", docstring="some docs" - ) + kwargs: dict[str, Any] = { + "set_cmd": None, + "label": "Parameter", + "unit": "a.u.", + "docstring": "some docs", + } if offset != NOT_PASSED: kwargs.update(offset=offset) diff --git a/tests/test_instrument.py b/tests/test_instrument.py index fd23723b25e6..e2bab00332ca 100644 --- a/tests/test_instrument.py +++ b/tests/test_instrument.py @@ -95,7 +95,7 @@ def test_validate_function(testdummy: DummyInstrument) -> None: testdummy.dac1.cache._value = 1000 # overrule the validator testdummy.dac1.cache._raw_value = 1000 # overrule the validator - with pytest.raises(Exception): + with pytest.raises(ValueError): testdummy.validate_status() @@ -121,11 +121,13 @@ def test_instrument_fail() -> None: @pytest.mark.usefixtures("close_before_and_after") def test_instrument_on_invalid_identifier() -> None: # Check if warning and error raised when invalid identifer name given - with pytest.warns( - UserWarning, match="Changed !-name to !_name for instrument identifier" + with ( + pytest.warns( + UserWarning, match="Changed !-name to !_name for instrument identifier" + ), + pytest.raises(ValueError, match="!_name invalid instrument identifier"), ): - with pytest.raises(ValueError, match="!_name invalid instrument identifier"): - DummyInstrument(name="!-name") + DummyInstrument(name="!-name") assert Instrument.instances() == [] assert DummyInstrument.instances() == [] @@ -277,7 +279,7 @@ def test_add_remove_f_p(testdummy) -> None: match="Use attributes directly on the instrument object instead", ): fcn = testdummy["function"] - assert isinstance(fcn, Function) + assert isinstance(fcn, Function) # by design, one gets the parameter if a function exists # and has same name with pytest.warns( @@ -285,7 +287,7 @@ def test_add_remove_f_p(testdummy) -> None: match="Use attributes directly on the instrument object instead", ): dac1 = testdummy["dac1"] - assert isinstance(dac1, Parameter) + assert isinstance(dac1, Parameter) def test_instances(testdummy, parabola) -> None: diff --git a/tests/test_logger.py b/tests/test_logger.py index a148a9657caa..956723f9b9ad 100644 --- a/tests/test_logger.py +++ b/tests/test_logger.py @@ -149,22 +149,23 @@ def test_start_logger_twice() -> None: def test_set_level_without_starting_raises() -> None: - with pytest.raises(RuntimeError): - with logger.console_level("DEBUG"): - pass + with pytest.raises(RuntimeError), logger.console_level("DEBUG"): + pass assert len(logging.getLogger().handlers) == NUM_PYTEST_LOGGERS def test_handler_level() -> None: logger.start_logger() with logger.LogCapture(level=logging.INFO) as logs: - logging.debug(TEST_LOG_MESSAGE) + logging.debug(TEST_LOG_MESSAGE) # noqa: LOG015 assert logs.value == "" - with logger.LogCapture(level=logging.INFO) as logs: - with logger.handler_level(level=logging.DEBUG, handler=logs.string_handler): - print(logs.string_handler) - logging.debug(TEST_LOG_MESSAGE) + with ( + logger.LogCapture(level=logging.INFO) as logs, + logger.handler_level(level=logging.DEBUG, handler=logs.string_handler), + ): + print(logs.string_handler) + logging.debug(TEST_LOG_MESSAGE) # noqa: LOG015 assert logs.value.strip() == TEST_LOG_MESSAGE @@ -177,9 +178,11 @@ def test_filter_instrument( # filter one instrument driver.cartesian((0, 0, 0)) - with logger.LogCapture(level=logging.DEBUG) as logs: - with logger.filter_instrument(mag_x, handler=logs.string_handler): - driver.cartesian((0, 0, 1)) + with ( + logger.LogCapture(level=logging.DEBUG) as logs, + logger.filter_instrument(mag_x, handler=logs.string_handler), + ): + driver.cartesian((0, 0, 1)) for line in logs.value.splitlines(): assert "[x(AMIModel430)]" in line assert "[y(AMIModel430)]" not in line @@ -187,9 +190,11 @@ def test_filter_instrument( # filter multiple instruments driver.cartesian((0, 0, 0)) - with logger.LogCapture(level=logging.DEBUG) as logs: - with logger.filter_instrument((mag_x, mag_y), handler=logs.string_handler): - driver.cartesian((0, 0, 1)) + with ( + logger.LogCapture(level=logging.DEBUG) as logs, + logger.filter_instrument((mag_x, mag_y), handler=logs.string_handler), + ): + driver.cartesian((0, 0, 1)) any_x = False any_y = False @@ -214,9 +219,8 @@ def test_filter_without_started_logger_raises( # filter one instrument driver.cartesian((0, 0, 0)) - with pytest.raises(RuntimeError): - with logger.filter_instrument(mag_x): - pass + with pytest.raises(RuntimeError), logger.filter_instrument(mag_x): + pass def test_capture_dataframe() -> None: diff --git a/tests/test_snapshot.py b/tests/test_snapshot.py index 86a4daffa039..124e9c7dfab2 100644 --- a/tests/test_snapshot.py +++ b/tests/test_snapshot.py @@ -58,7 +58,6 @@ def test_snapshot_skip_params_update( (["v1", "v2", "v3", "v4"], ["v2"]), (["v1", "v2", "v3", "v4"], ["v3"]), (["v1", "v2", "v3", "v4"], ["v4"]), - (["v1", "v2", "v3", "v4"], ["v4"]), (["v1", "v2", "v3", "v4"], ["v1", "v2"]), (["v1", "v2", "v3", "v4"], []), ], diff --git a/tests/test_station.py b/tests/test_station.py index 89eedca4992f..01ec4388559c 100644 --- a/tests/test_station.py +++ b/tests/test_station.py @@ -619,7 +619,7 @@ def test_setup_alias_parameters() -> None: """ ) mock = st.load_instrument("mock") - p = getattr(mock, "gate_a") + p = mock.gate_a assert isinstance(p, Parameter) assert p.unit == "mV" assert p.label == "main gate" @@ -665,7 +665,7 @@ def test_setup_delegate_parameters() -> None: """ ) mock = st.load_instrument("mock") - p = getattr(mock, "gate_a") + p = mock.gate_a assert isinstance(p, DelegateParameter) assert p.unit == "mV" assert p.label == "main gate"