Skip to content

Commit

Permalink
Merge pull request #5467 from jenshnielsen/ruff_rules
Browse files Browse the repository at this point in the history
Implement 2 more ruff rules
  • Loading branch information
jenshnielsen authored Oct 30, 2023
2 parents 63e2eb4 + 9f152f8 commit 68051a7
Show file tree
Hide file tree
Showing 48 changed files with 453 additions and 270 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ filterwarnings = [
# I isort
# ISC flake8-implicit-str-concat
# TID253 banned-module-level-imports
select = ["E", "F", "PT025", "UP", "RUF200", "I", "G", "ISC", "TID253"]
select = ["E", "F", "PT025", "UP", "RUF010", "RUF012", "RUF200", "I", "G", "ISC", "TID253"]
# darker will fix this as code is
# reformatted when it is changed.
# We have a lot of use of f strings in log messages
Expand Down
8 changes: 4 additions & 4 deletions src/qcodes/configuration/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ class Config:
"""Filename of default config"""
current_config_path = default_file_name
"""Path of the last loaded config file"""
_loaded_config_files = [default_file_name]

# get abs path of schema file
schema_default_file_name = str(files(_PARENT_MODULE) / schema_file_name)
Expand Down Expand Up @@ -84,15 +83,16 @@ class Config:
defaults_schema: DotDict
"""The default schema"""

_diff_config: dict[str, Any] = {}
_diff_schema: dict[str, Any] = {}

def __init__(self, path: str | None = None) -> None:
"""
Args:
path: Optional path to directory containing
a `qcodesrc.json` config file
"""
self._loaded_config_files = [self.default_file_name]
self._diff_config: dict[str, Any] = {}
self._diff_schema: dict[str, Any] = {}

self.config_file_path = path
self.defaults, self.defaults_schema = self.load_default()
self.update_config()
Expand Down
5 changes: 2 additions & 3 deletions src/qcodes/dataset/descriptions/param_spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from collections.abc import Sequence
from copy import deepcopy
from typing import Any
from typing import Any, ClassVar

from typing_extensions import TypedDict

Expand All @@ -20,8 +20,7 @@ class ParamSpecDict(ParamSpecBaseDict):


class ParamSpecBase:

allowed_types = ['array', 'numeric', 'text', 'complex']
allowed_types: ClassVar[list[str]] = ["array", "numeric", "text", "complex"]

def __init__(
self,
Expand Down
2 changes: 1 addition & 1 deletion src/qcodes/dataset/measurements.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ def _unpack_partial_result(
else:
err_msg = (
"Can not add result for parameter "
f"{str(param)} or {str_or_register_name(param)},"
f"{param!s} or {str_or_register_name(param)},"
"no such parameter registered "
"with this measurement."
)
Expand Down
2 changes: 1 addition & 1 deletion src/qcodes/instrument/channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -791,7 +791,7 @@ def validate(self, value: InstrumentChannel, context: str = '') -> None:
"""
if value not in self._channel_list:
raise ValueError(
f"{repr(value)} is not part of the expected channel list; {context}"
f"{value!r} is not part of the expected channel list; {context}"
)


Expand Down
4 changes: 2 additions & 2 deletions src/qcodes/instrument/instrument_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import logging
import warnings
from collections.abc import Callable, Mapping, Sequence
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING, Any, ClassVar

import numpy as np

Expand Down Expand Up @@ -578,7 +578,7 @@ def _is_abstract(self) -> bool:
# instrument.get('someparam') === instrument['someparam'].get() #
# etc... #
#
delegate_attr_dicts = ["parameters", "functions", "submodules"]
delegate_attr_dicts: ClassVar[list[str]] = ["parameters", "functions", "submodules"]

def __getitem__(self, key: str) -> Callable[..., Any] | Parameter:
"""Delegate instrument['name'] to parameter or function 'name'."""
Expand Down
2 changes: 1 addition & 1 deletion src/qcodes/instrument/ip_to_visa.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def __init__(

traversable_handle = files("qcodes.instrument.sims") / pyvisa_sim_file
with as_file(traversable_handle) as sim_visalib_path:
self.visalib = f"{str(sim_visalib_path)}@sim"
self.visalib = f"{sim_visalib_path!s}@sim"
self.set_address(address=address)

if device_clear:
Expand Down
15 changes: 5 additions & 10 deletions src/qcodes/instrument/mockers/ami430.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import re
import time
from datetime import datetime
from typing import ClassVar


class MockAMI430:
states = {
states: ClassVar[dict[str, str]] = {
"RAMPING to target field/current": "1",
"HOLDING at the target field/current": "2",
"PAUSED": "3",
Expand All @@ -17,17 +18,11 @@ class MockAMI430:
"Cooling persistent switch": "10"
}

field_units = {
"tesla": "1",
"kilogauss": "0"
}
field_units: ClassVar[dict[str, str]] = {"tesla": "1", "kilogauss": "0"}

ramp_rate_units = {
"A/s": "0",
"A/min": "1"
}
ramp_rate_units: ClassVar[dict[str, str]] = {"A/s": "0", "A/min": "1"}

quench_state = {False: "0", True: "1"}
quench_state: ClassVar[dict[bool, str]] = {False: "0", True: "1"}

def __init__(self, name):

Expand Down
4 changes: 2 additions & 2 deletions src/qcodes/instrument/mockers/simulated_ats_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@


import ctypes
from typing import Any, Callable, Optional
from typing import Any, Callable, ClassVar, Optional

import numpy as np

Expand All @@ -23,7 +23,7 @@

class SimulatedATS9360API(AlazarATSAPI):

registers = {
registers: ClassVar[dict[int, int]] = {
8: 70254688,
58: int(np.uint32(1 << 26)) # Trigger hold off
}
Expand Down
2 changes: 1 addition & 1 deletion src/qcodes/instrument/visa.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def __init__(
"could not be found. Trying to load "
f"file {pyvisa_sim_file} from module: {module}"
)
visalib = f"{str(sim_visalib_path)}@sim"
visalib = f"{sim_visalib_path!s}@sim"
(
visa_handle,
visabackend,
Expand Down
4 changes: 2 additions & 2 deletions src/qcodes/instrument_drivers/AimTTi/_AimTTi_PL_P.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, Optional
from typing import Any, ClassVar, Optional

from qcodes import validators as vals
from qcodes.instrument import ChannelList, Instrument, InstrumentChannel, VisaInstrument
Expand Down Expand Up @@ -214,7 +214,7 @@ class AimTTi(VisaInstrument):
Tested with Aim TTi PL601-P equipped with a single output channel.
"""

_numOutputChannels = {
_numOutputChannels: ClassVar[dict[str, int]] = {
"PL068-P": 1,
"PL155-P": 1,
"PL303-P": 1,
Expand Down
10 changes: 6 additions & 4 deletions src/qcodes/instrument_drivers/AlazarTech/ATS9360.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,10 +318,12 @@ def __init__(self, name: str,
get_cmd=self._get_trigger_holdoff,
set_cmd=self._set_trigger_holdoff)

model = self.get_idn()['model']
if model != 'ATS9360':
raise Exception(f"The Alazar board kind is not 'ATS9360',"
f" found '{str(model)}' instead.")
model = self.get_idn()["model"]
if model != "ATS9360":
raise Exception(
f"The Alazar board kind is not 'ATS9360',"
f" found '{model!s}' instead."
)

def _get_trigger_holdoff(self) -> bool:
fwversion = self.get_idn()['firmware']
Expand Down
10 changes: 6 additions & 4 deletions src/qcodes/instrument_drivers/AlazarTech/ATS9373.py
Original file line number Diff line number Diff line change
Expand Up @@ -334,10 +334,12 @@ def __init__(self, name: str,
get_cmd=self._get_trigger_holdoff,
set_cmd=self._set_trigger_holdoff)

model = self.get_idn()['model']
if model != 'ATS9373':
raise Exception(f"The Alazar board kind is not 'ATS9373',"
f" found '{str(model)}' instead.")
model = self.get_idn()["model"]
if model != "ATS9373":
raise Exception(
f"The Alazar board kind is not 'ATS9373',"
f" found '{model!s}' instead."
)

def _get_trigger_holdoff(self) -> bool:
fwversion = self.get_idn()["firmware"]
Expand Down
10 changes: 6 additions & 4 deletions src/qcodes/instrument_drivers/AlazarTech/ATS9870.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,10 +301,12 @@ def __init__(self, name: str,
initial_value=1000,
vals=validators.Ints(min_value=0))

model = self.get_idn()['model']
if model != 'ATS9870':
raise Exception(f"The Alazar board kind is not 'ATS9870',"
f" found '{str(model)}' instead.")
model = self.get_idn()["model"]
if model != "ATS9870":
raise Exception(
f"The Alazar board kind is not 'ATS9870',"
f" found '{model!s}' instead."
)


class AlazarTech_ATS9870(AlazarTechATS9870):
Expand Down
4 changes: 2 additions & 2 deletions src/qcodes/instrument_drivers/AlazarTech/ats_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import ctypes
from ctypes import POINTER
from typing import Any, Union
from typing import Any, ClassVar, Union

# `ParameterBase` is needed because users may pass instrument parameters
# that originate from `Instrument.parameters` dictionary which is typed
Expand Down Expand Up @@ -51,7 +51,7 @@ class AlazarATSAPI(WrappedDll):

## ACTUAL DLL API FUNCTIONS ##

signatures: dict[str, Signature] = {}
signatures: ClassVar[dict[str, Signature]] = {}

def set_trigger_time_out(self,
handle: int,
Expand Down
4 changes: 2 additions & 2 deletions src/qcodes/instrument_drivers/AlazarTech/dll_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from collections.abc import Callable, Sequence
from functools import partial
from threading import Lock
from typing import Any, NamedTuple, NewType, TypeVar
from typing import Any, ClassVar, NamedTuple, NewType, TypeVar
from weakref import WeakValueDictionary

from qcodes.parameters import ParameterBase
Expand Down Expand Up @@ -144,7 +144,7 @@ class WrappedDll(metaclass=DllWrapperMeta):
dll_path: Path to the DLL library to load and wrap
"""

signatures: dict[str, Signature] = {}
signatures: ClassVar[dict[str, Signature]] = {}
"""
Signatures for loaded DLL functions;
It is to be filled with :class:`Signature` instances for the DLL
Expand Down
15 changes: 10 additions & 5 deletions src/qcodes/instrument_drivers/Keithley/Keithley_2450.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from types import TracebackType
from typing import Any, Optional, Union, cast
from typing import Any, ClassVar, Optional, Union, cast

import numpy as np
from typing_extensions import TypedDict
Expand Down Expand Up @@ -46,9 +46,9 @@ class Keithley2450Buffer(InstrumentChannel):
Treat the reading buffer as a submodule, similar to Sense and Source
"""

default_buffer = {"defbuffer1", "defbuffer2"}
default_buffer: ClassVar[set[str]] = {"defbuffer1", "defbuffer2"}

buffer_elements = {
buffer_elements: ClassVar[dict[str, str]] = {
"date": "DATE",
"measurement_formatted": "FORMatted",
"fractional_seconds": "FRACtional",
Expand Down Expand Up @@ -202,6 +202,11 @@ def delete(self) -> None:
self.write(f":TRACe:DELete '{self.buffer_name}'")


class _FunctionMode(TypedDict):
name: str
unit: str
range_vals: Numbers

class Keithley2450Sense(InstrumentChannel):
"""
The sense module of the Keithley 2450 SMU.
Expand All @@ -217,7 +222,7 @@ class Keithley2450Sense(InstrumentChannel):
which returns the proper submodule for any given function mode
"""

function_modes = {
function_modes: ClassVar[dict[str, _FunctionMode]] = {
"current": {"name": '"CURR:DC"', "unit": "A", "range_vals": Numbers(10e-9, 1)},
"resistance": {
"name": '"RES"',
Expand Down Expand Up @@ -372,7 +377,7 @@ class Keithley2450Source(InstrumentChannel):
which returns the proper submodule for any given function mode
"""

function_modes = {
function_modes: ClassVar[dict[str, _FunctionMode]] = {
"current": {"name": "CURR", "unit": "A", "range_vals": Numbers(-1, 1)},
"voltage": {"name": "VOLT", "unit": "V", "range_vals": Numbers(-200, 200)},
}
Expand Down
16 changes: 11 additions & 5 deletions src/qcodes/instrument_drivers/Keithley/Keithley_7510.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from collections.abc import Sequence
from types import TracebackType
from typing import Any, Optional, Union, cast
from typing import Any, ClassVar, Optional, TypedDict, Union, cast

import numpy as np

Expand Down Expand Up @@ -79,9 +79,9 @@ class Keithley7510Buffer(InstrumentChannel):
Treat the reading buffer as a submodule, similar to Sense.
"""

default_buffer = {"defbuffer1", "defbuffer2"}
default_buffer: ClassVar[set[str]] = {"defbuffer1", "defbuffer2"}

buffer_elements = {
buffer_elements: ClassVar[dict[str, str]] = {
"date": "DATE",
"measurement_formatted": "FORMatted",
"fractional_seconds": "FRACtional",
Expand Down Expand Up @@ -389,6 +389,12 @@ def delete(self) -> None:
self.write(f":TRACe:DELete '{self.short_name}'")


class _FunctionMode(TypedDict):
name: str
unit: str
range_vals: Optional[Numbers]


class Keithley7510Sense(InstrumentChannel):
"""
The sense module of the Keithley 7510 DMM, based on the sense module of
Expand All @@ -411,7 +417,7 @@ class Keithley7510Sense(InstrumentChannel):
which returns the proper submodule for any given function mode.
"""

function_modes = {
function_modes: ClassVar[dict[str, _FunctionMode]] = {
"voltage": {
"name": '"VOLT:DC"',
"unit": "V",
Expand Down Expand Up @@ -589,7 +595,7 @@ class Keithley7510DigitizeSense(InstrumentChannel):
The Digitize sense module of the Keithley 7510 DMM.
"""

function_modes: dict[str, dict[str, Any]] = {
function_modes: ClassVar[dict[str, _FunctionMode]] = {
"None": {"name": '"NONE"', "unit": "", "range_vals": None},
"voltage": {
"name": '"VOLT"',
Expand Down
6 changes: 3 additions & 3 deletions src/qcodes/instrument_drivers/Keithley/Keithley_s46.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"""
import re
from itertools import product
from typing import Any, Optional
from typing import Any, ClassVar, Optional

from qcodes.instrument import Instrument, VisaInstrument
from qcodes.parameters import Parameter, ParamRawDataType
Expand Down Expand Up @@ -128,13 +128,13 @@ class KeithleyS46(VisaInstrument):

# Make a dictionary where keys are channel aliases (e.g. 'A1', 'B3', etc)
# and values are corresponding channel numbers.
channel_numbers: dict[str, int] = {
channel_numbers: ClassVar[dict[str, int]] = {
f"{a}{b}": count + 1
for count, (a, b) in enumerate(product(["A", "B", "C", "D"], range(1, 7)))
}
channel_numbers.update({f"R{i}": i + 24 for i in range(1, 9)})
# Make a reverse dict for efficient alias lookup given a channel number
aliases = {v: k for k, v in channel_numbers.items()}
aliases: ClassVar[dict[int, str]] = {v: k for k, v in channel_numbers.items()}

def __init__(self, name: str, address: str, **kwargs: Any):

Expand Down
Loading

0 comments on commit 68051a7

Please sign in to comment.