Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor types to check with pyright #4894

Merged
merged 89 commits into from
Jan 4, 2023
Merged
Show file tree
Hide file tree
Changes from 88 commits
Commits
Show all changes
89 commits
Select commit Hold shift + click to select a range
dcd82df
Add missing imports
jenshnielsen Dec 22, 2022
7d5fa3d
Pyright prevent level from being unassigned
jenshnielsen Dec 22, 2022
991f886
Avoid exception if ms is unasigned
jenshnielsen Dec 22, 2022
afbf2f3
handle that yaml merger could throw if given zero files
jenshnielsen Dec 22, 2022
b7b0395
pyright fix warning in matplotlib helpers
jenshnielsen Dec 22, 2022
61eee33
pyright exclude unwanted modules
jenshnielsen Dec 22, 2022
5c95e8d
pyright fix validators
jenshnielsen Dec 22, 2022
eae4cf6
pyright remove redundant annotation
jenshnielsen Dec 22, 2022
27a0d68
pyright make val_mapping type check
jenshnielsen Dec 22, 2022
ac18a2e
Exclude one more
jenshnielsen Dec 22, 2022
d33d443
Pyright fix threading
jenshnielsen Dec 22, 2022
78a989f
pyright partial fix n52xx
jenshnielsen Dec 22, 2022
90ea968
pyright awg silence incorrect warning
jenshnielsen Dec 22, 2022
b669b45
Handle potenially incorrect data format
jenshnielsen Dec 22, 2022
0a02fc7
Help pyright figure out command
jenshnielsen Dec 23, 2022
9fc091d
Pyright does not considder Type[None] as Type[Object]
jenshnielsen Dec 23, 2022
d1da594
Make it clear to pyright that if/else is exhaustive
jenshnielsen Dec 23, 2022
7c7db72
Pyright fix ami driver
jenshnielsen Dec 23, 2022
abd673d
pyright fix b1500
jenshnielsen Dec 23, 2022
766247a
use ... not pass with protocol
jenshnielsen Dec 23, 2022
b086500
Basedataset is also a protocol
jenshnielsen Dec 23, 2022
e1c405b
Exp container
jenshnielsen Dec 23, 2022
e9f9454
Keysight 344xxA
jenshnielsen Dec 23, 2022
3918cff
qdac fix potentially incorrect imports
jenshnielsen Dec 23, 2022
4577b55
use cast to fix typenarrowing not working with unknown
jenshnielsen Dec 23, 2022
9e4d907
pyright cast Any to bool
jenshnielsen Dec 23, 2022
811270a
Avoid setting module to None
jenshnielsen Dec 23, 2022
7f3dde9
Avoid datasavers potentially undefined
jenshnielsen Dec 23, 2022
68e3822
clarify that write period is fload when read from config
jenshnielsen Dec 23, 2022
ba0129f
Small improvement to command types
jenshnielsen Dec 24, 2022
49e7974
Handle that pyright does not understand this is only used in in mem c…
jenshnielsen Dec 25, 2022
3e65445
fix typechecking for plotting
jenshnielsen Dec 25, 2022
6dabefc
Fix use outside loop
jenshnielsen Dec 25, 2022
f5c5c9d
handle typing with untyped logic
jenshnielsen Dec 25, 2022
ff7ac12
Don't check qcmatplotlib
jenshnielsen Dec 25, 2022
af33214
report missing types
jenshnielsen Dec 25, 2022
57ef4d5
fix types in interactive widget
jenshnielsen Dec 26, 2022
7a6dff9
exclude a few more untyped modules
jenshnielsen Dec 27, 2022
7ca6cbf
add a temp variable to help with type inference
jenshnielsen Dec 27, 2022
d99835d
Aviod inconsistent order due to multiple inheritance
jenshnielsen Dec 27, 2022
9609f6d
use tuple rather than list to make covariant
jenshnielsen Dec 27, 2022
dce217f
guid helpers ensure conn always defined
jenshnielsen Dec 27, 2022
97c69d2
connection ensure old level is always defined
jenshnielsen Dec 27, 2022
e15a056
qdev qdac ensure module is always imported
jenshnielsen Dec 27, 2022
203ac16
qdev qdac asign version in __init__
jenshnielsen Dec 27, 2022
445b33d
sqlite ensure varibles are always defined
jenshnielsen Dec 27, 2022
3c12a28
drivers ensure variables are always defined
jenshnielsen Dec 27, 2022
da9d483
Znb return float as documented not numpy types
jenshnielsen Dec 27, 2022
8a47bc0
sqlite settings avoid None value for parameter
jenshnielsen Dec 27, 2022
dafc6b0
use ... not pass in protocol
jenshnielsen Dec 27, 2022
c534dd3
fix undefined var in magic
jenshnielsen Dec 27, 2022
a392fe6
silence warning in pyqt code
jenshnielsen Dec 27, 2022
dcb0eca
fix matplotlib related typing
jenshnielsen Dec 27, 2022
067dfdc
update dond to reflect that we return tuples
jenshnielsen Dec 29, 2022
334ed1e
pyright disable spyder related warnings
jenshnielsen Dec 29, 2022
ff209e2
cannot get None for limit
jenshnielsen Dec 29, 2022
83ef2d1
return ancestors as tuple
jenshnielsen Dec 29, 2022
5b6d4ba
help with extend type
jenshnielsen Dec 29, 2022
fc30d11
ignore lomentum import
jenshnielsen Dec 29, 2022
e5d37ad
pyright ignore warnings in deprecate
jenshnielsen Dec 29, 2022
3bff3b0
ignore some more pyright issues
jenshnielsen Dec 29, 2022
7fe3d53
ignore variable that pyright thinks is unassigned
jenshnielsen Dec 29, 2022
7f23329
add some dtypes to np arrays for pyright type checking
jenshnielsen Dec 29, 2022
ea40bc2
help pyright figure out that code_str is not None
jenshnielsen Dec 29, 2022
59ffbb2
Ensure that interrupted is always asigned
jenshnielsen Dec 30, 2022
1ad9009
Prevent parameter to be added to a ChannelTuple which would be an error
jenshnielsen Dec 30, 2022
c301563
Fix channellogic to reflect correct baseclass
jenshnielsen Dec 30, 2022
bab0fb7
fix typecheck in queries
jenshnielsen Dec 30, 2022
b892967
Typecheck ensure that idnparts is always assigned
jenshnielsen Dec 30, 2022
f726070
correct delegate cache to match regular
jenshnielsen Dec 30, 2022
f577f8c
fix typechecking in galil driveR
jenshnielsen Dec 30, 2022
7967fd4
ignore error in alazar driver
jenshnielsen Dec 30, 2022
f879602
ignore incorrect error in keithley driver
jenshnielsen Dec 30, 2022
4552a8f
ignore warnings in plotting
jenshnielsen Dec 30, 2022
2b4c7af
fix incorrect formatting
jenshnielsen Dec 30, 2022
51f9f1d
fix mypy type checking
jenshnielsen Dec 31, 2022
229b208
exclude slack extension from pyright
jenshnielsen Dec 31, 2022
3bc0f3a
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jan 2, 2023
9be3f1e
use python 3.8 compatible types
jenshnielsen Jan 2, 2023
3b9d6b9
pyright dont require clr to be installed
jenshnielsen Jan 2, 2023
06de00a
prevent black/darker from moving comment
jenshnielsen Jan 2, 2023
512c851
bump min typing extensions for NotRequired
jenshnielsen Jan 2, 2023
1504562
Add type stubs as git submodule
jenshnielsen Jan 3, 2023
09ba7b2
Update qcodes/validators/validators.py
jenshnielsen Jan 3, 2023
c0c0fc1
Update typing stubs submodule to include generated stubs
jenshnielsen Jan 3, 2023
bb0b236
fix pyright ipython errors
jenshnielsen Jan 3, 2023
63cd8d1
fix string formatting
jenshnielsen Jan 4, 2023
1cfe3a0
Document breaking changes in refactor
jenshnielsen Jan 4, 2023
d115000
Update docs/changes/newsfragments/4894.breaking
jenshnielsen Jan 4, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,6 @@
path = qcodes/tests/dataset/fixtures/db_files
url = https://github.com/QCoDeS/qcodes_db_fixtures.git
branch = main
[submodule "typings"]
path = typings
url = https://github.com/QCoDeS/qcodes-python-type-stubs.git
5 changes: 5 additions & 0 deletions docs/changes/newsfragments/4894.breaking
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
``InstrumentBase.ancestors`` now returns a tuple of ancestors
to the current Instrument, Instrumentchannel or Instrumentmodule and not a list.
jenshnielsen marked this conversation as resolved.
Show resolved Hide resolved

``dond ``, ``do1d`` etc. now returns tuples of Matplotlib axes and colorbars
when plotting and not lists.
21 changes: 20 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ dependencies = [
"pyvisa>=1.11.0, <1.14.0",
"ruamel.yaml>=0.16.0,!=0.16.6",
"tabulate>=0.8.0",
"typing_extensions>=3.10.0",
"typing_extensions>=4.0.0",
"tqdm>=4.32.2",
"uncertainties>=3.1.4",
"versioningit>=2.0.1",
Expand Down Expand Up @@ -228,6 +228,25 @@ module = [
]
ignore_missing_imports = true

[tool.pyright]
include = ["qcodes"]
ignore = [
"qcodes/tests",
"qcodes/instrument_drivers/test.py",
"qcodes/instrument_drivers/zurich_instruments",
"qcodes/instrument_drivers/Harvard/Decadac.py",
"qcodes/instrument_drivers/oxford/mercuryiPS.py",
"qcodes/actions.py",
"qcodes/data",
"qcodes/loops.py",
"qcodes/measure.py",
"qcodes/plots/pyqtgraph.py",
"qcodes/plots/qcmatplotlib.py",
"qcodes/plots/base.py",
"qcodes/extensions/slack.py"
]
reportMissingTypeStubs = true

[tool.pytest.ini_options]
minversion = "6.0"
junit_family = "legacy"
Expand Down
24 changes: 16 additions & 8 deletions qcodes/dataset/data_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -1229,8 +1229,9 @@ def _enqueue_results(

toplevel_params = (set(interdeps.dependencies)
.intersection(set(result_dict)))
if self._in_memory_cache:
new_results: dict[str, dict[str, numpy.ndarray]] = {}

new_results: dict[str, dict[str, numpy.ndarray]] = {}

for toplevel_param in toplevel_params:
inff_params = set(interdeps.inferences.get(toplevel_param, ()))
deps_params = set(interdeps.dependencies.get(toplevel_param, ()))
Expand Down Expand Up @@ -1353,7 +1354,7 @@ def _finalize_res_dict_numeric_text_or_complex(
flat_results[dep.name] = result_dict[dep].ravel()
for inff in inff_params:
if numpy.shape(result_dict[inff]) == ():
flat_results[inff.name] = numpy.repeat(result_dict[dep], N)
jenshnielsen marked this conversation as resolved.
Show resolved Hide resolved
flat_results[inff.name] = numpy.repeat(result_dict[inff], N)
else:
flat_results[inff.name] = result_dict[inff].ravel()

Expand All @@ -1375,21 +1376,28 @@ def _finalize_res_dict_standalones(
for param, value in result_dict.items():
if param.type == 'text':
if value.shape:
res_list += [{param.name: str(val)} for val in value]
new_res: list[dict[str, VALUE]] = [
{param.name: str(val)} for val in value
]
res_list += new_res
else:
res_list += [{param.name: str(value)}]
new_res = [{param.name: str(value)}]
res_list += new_res
elif param.type == 'numeric':
if value.shape:
res_list += [{param.name: number} for number in value]
else:
res_list += [{param.name: float(value)}]
new_res = [{param.name: float(value)}]
res_list += new_res
elif param.type == 'complex':
if value.shape:
res_list += [{param.name: number} for number in value]
else:
res_list += [{param.name: complex(value)}]
new_res = [{param.name: complex(value)}]
res_list += new_res
else:
res_list += [{param.name: value}]
new_res = [{param.name: value}]
res_list += new_res

return res_list

Expand Down
91 changes: 47 additions & 44 deletions qcodes/dataset/data_set_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ class CompletedError(RuntimeError):


@runtime_checkable
class DataSetProtocol(Protocol, Sized):
class DataSetProtocol(Protocol):

# the "persistent traits" are the attributes/properties of the DataSet
# that are NOT tied to the representation of the DataSet in any particular
Expand Down Expand Up @@ -116,114 +116,114 @@ def prepare(
parent_datasets: Sequence[Mapping[Any, Any]] = (),
write_in_background: bool = False,
) -> None:
pass
...

@property
def pristine(self) -> bool:
pass
...

@property
def running(self) -> bool:
pass
...

@property
def completed(self) -> bool:
pass
...

def mark_completed(self) -> None:
pass
...

# dataset attributes

@property
def run_id(self) -> int:
pass
...

@property
def captured_run_id(self) -> int:
pass
...

@property
def counter(self) -> int:
pass
...

@property
def captured_counter(self) -> int:
pass
...

@property
def guid(self) -> str:
pass
...

@property
def number_of_results(self) -> int:
pass
...

@property
def name(self) -> str:
pass
...

@property
def exp_name(self) -> str:
pass
...

@property
def exp_id(self) -> int:
pass
...

@property
def sample_name(self) -> str:
pass
...

def run_timestamp(self, fmt: str = "%Y-%m-%d %H:%M:%S") -> str | None:
pass
...

@property
def run_timestamp_raw(self) -> float | None:
pass
...

def completed_timestamp(self, fmt: str = "%Y-%m-%d %H:%M:%S") -> str | None:
pass
...

@property
def completed_timestamp_raw(self) -> float | None:
pass
...

# snapshot and metadata
@property
def snapshot(self) -> dict[str, Any] | None:
pass
...

def add_snapshot(self, snapshot: str, overwrite: bool = False) -> None:
pass
...

@property
def _snapshot_raw(self) -> str | None:
pass
...

def add_metadata(self, tag: str, metadata: Any) -> None:
pass
...

@property
def metadata(self) -> dict[str, Any]:
pass
...

@property
def path_to_db(self) -> str | None:
pass
...

# dataset description and links
@property
def paramspecs(self) -> dict[str, ParamSpec]:
pass
...

@property
def description(self) -> RunDescriber:
pass
...

@property
def parent_dataset_links(self) -> list[Link]:
pass
...

# data related members

Expand All @@ -233,15 +233,15 @@ def export(
path: str | None = None,
prefix: str | None = None,
) -> None:
pass
...

@property
def export_info(self) -> ExportInfo:
pass
...

@property
def cache(self) -> DataSetCache[DataSetProtocol]:
pass
...

def get_parameter_data(
self,
Expand All @@ -250,15 +250,15 @@ def get_parameter_data(
end: int | None = None,
callback: Callable[[float], None] | None = None,
) -> ParameterData:
pass
...

def get_parameters(self) -> SPECS:
# used by plottr
pass
...

@property
def dependent_parameters(self) -> tuple[ParamSpecBase, ...]:
pass
...

# exporters to other in memory formats

Expand All @@ -268,49 +268,52 @@ def to_xarray_dataarray_dict(
start: int | None = None,
end: int | None = None,
) -> dict[str, xr.DataArray]:
pass
...

def to_xarray_dataset(
self,
*params: str | ParamSpec | ParameterBase,
start: int | None = None,
end: int | None = None,
) -> xr.Dataset:
pass
...

def to_pandas_dataframe_dict(
self,
*params: str | ParamSpec | ParameterBase,
start: int | None = None,
end: int | None = None,
) -> dict[str, pd.DataFrame]:
pass
...

def to_pandas_dataframe(
self,
*params: str | ParamSpec | ParameterBase,
start: int | None = None,
end: int | None = None,
) -> pd.DataFrame:
pass
...

# private members called by various other parts or the api

def _enqueue_results(self, result_dict: Mapping[ParamSpecBase, np.ndarray]) -> None:
pass
...

def _flush_data_to_database(self, block: bool = False) -> None:
pass
...

@property
def _parameters(self) -> str | None:
pass
...

def _set_export_info(self, export_info: ExportInfo) -> None:
pass
...

def __len__(self) -> int:
...

class BaseDataSet(DataSetProtocol):

class BaseDataSet(DataSetProtocol, Protocol):

# shared methods between all implementations of the dataset

Expand Down
4 changes: 2 additions & 2 deletions qcodes/dataset/dond/do_0d.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

import logging
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, cast

from qcodes import config
from qcodes.parameters import ParameterBase
Expand Down Expand Up @@ -54,7 +54,7 @@ def do0d(
The QCoDeS dataset.
"""
if do_plot is None:
do_plot = config.dataset.dond_plot
do_plot = cast(bool, config.dataset.dond_plot)
meas = Measurement(name=measurement_name, exp=exp)
if log_info is not None:
meas._extra_log_info = log_info
Expand Down
4 changes: 2 additions & 2 deletions qcodes/dataset/dond/do_1d.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import logging
import sys
import time
from typing import TYPE_CHECKING, Sequence
from typing import TYPE_CHECKING, Sequence, cast

import numpy as np
from tqdm.auto import tqdm
Expand Down Expand Up @@ -101,7 +101,7 @@ def do1d(
The QCoDeS dataset.
"""
if do_plot is None:
do_plot = config.dataset.dond_plot
do_plot = cast(bool, config.dataset.dond_plot)
if show_progress is None:
show_progress = config.dataset.dond_show_progress

Expand Down
Loading