Skip to content

Support type checking with TY - #8441

Draft
Jens Hedegaard Nielsen (jenshnielsen) wants to merge 78 commits into
microsoft:mainfrom
jenshnielsen:ty_0_73_support_1
Draft

Jens Hedegaard Nielsen (jenshnielsen) wants to merge 78 commits into
microsoft:mainfrom
jenshnielsen:ty_0_73_support_1

Conversation

@jenshnielsen

Copy link
Copy Markdown
Collaborator

WIP pr. Will be broken up to review in smaller bits

@codecov

codecov Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 80.76923% with 15 lines in your changes missing coverage. Please review.
✅ Project coverage is 78.56%. Comparing base (e4b6800) to head (bb55b8a).

Files with missing lines Patch % Lines
src/qcodes/dataset/data_set.py 0.00% 7 Missing ⚠️
src/qcodes/parameters/parameter.py 87.50% 3 Missing ⚠️
src/qcodes/dataset/json_exporter.py 0.00% 2 Missing ⚠️
src/qcodes/dataset/data_set_in_memory.py 66.66% 1 Missing ⚠️
...codes/instrument_drivers/AlazarTech/dll_wrapper.py 0.00% 1 Missing ⚠️
...ivers/QuantumDesign/DynaCoolPPMS/private/server.py 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #8441      +/-   ##
==========================================
+ Coverage   78.55%   78.56%   +0.01%     
==========================================
  Files         311      311              
  Lines       33162    33179      +17     
==========================================
+ Hits        26049    26067      +18     
+ Misses       7113     7112       -1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

These lines deliberately pass invalid arguments or subscripts, or mock
attributes that are not declared on the annotated type, to check the
runtime error handling. They are already suppressed for pyright.
The tuple only contains numpy types but was annotated as also containing
the builtin complex. Since complex in an annotation implicitly means
int or float or complex, that made calls such as complex_type(1 + 2j)
be checked against int and float too.
Without an annotation ty infers the type of the module level constant
from its default value, so reassigning WEBSOCKET_PORT to select another
port, as the test suite does, is an error.
The element type of an unannotated dict or list literal is inferred from
its content, and containers are invariant, so a literal such as
{name: (11, 11)} is not a dict[str, tuple[int, ...]]. Declare the type
that the receiving function expects instead.
Parameter.step and DelegateParameter.source are optional and are read
back through a property, so a type checker cannot know that the value
assigned earlier in the test is still there.
ty requires a legacy TypeVar to be assigned to a variable matching its
name, so it rejects the ones these tests store straight into a dict.
They are values handed to _make_deprecated_typevars_getattr rather than
type variables used to parametrize anything, and both mypy and pyright
accept them.
The wrapped callable is a function in practice but its declared type
does not guarantee that. mypy and pyright both accept the attribute
access.
The test cells imported the Weinschel8320 driver from qcodes, replacing
the class of the same name that the notebook defines, which ty reports
as an invalid assignment. Remove those imports so the tests use the
driver from the notebook, and annotate the fixtures and tests.
test_init_v2 requested a driver fixture that does not exist, so request
weinschel_driver_2 instead. Also clear the stale output of the first
cell.
IDN returns the dict produced by get_idn. Annotate it as
Parameter[dict[str, str], Self]. Strictly the values may be None, but
including that would require asserts at every use.

The Weinschel 8320 test treated the result as a string. It only runs
with an instance of the driver, so this went unnoticed. Check the
vendor and model instead.
ty warns that testing a callable for truthiness is likely a missing
call. Checking for None instead states what is meant and matches how
ParameterBase itself guards the callback.
The invalid types assigned in test_parameter_mixin and the float passed
to get_level_code are deliberate, and are already suppressed for mypy.
The type annotations added to the tests on main come with pyright and
mypy suppressions on the lines that pass invalid types on purpose,
mostly to check runtime error handling. Suppress the corresponding ty
errors too.
The test inputs these casts were narrowing are now annotated, so the
values already have the type the casts asserted.
Annotate the spectrum data as one dimensional so iterating it yields
scalars, annotate the list of ParamSpecDicts so the dict literals are
checked against the TypedDict, and mock the ask method of the Keysight
34465A with patch.object rather than assigning to the method.
The values are stored in a list, so integer keys already worked at
runtime.
These tests pass values that do not match the annotated value type of
the parameter on purpose, either to check that they are rejected or
that the strings and integers accepted by the on/off mapping still
work. They are already suppressed for pyright.
The trigger count tests of the Keithley 6500 pass floats and strings
to an int parameter, to check that whole floats are accepted and that
invalid values are rejected. The parameter access tests check that a
record has no parameter attribute and that its value is read only, and
read the extra attributes that logging adds to a LogRecord. These are
already suppressed for pyright or mypy.
The exc_info of a LogRecord is False rather than None when a message is
logged with exc_info=False, so checking that it is not None does not
make it safe to index. Check that it is truthy instead.
The product of the setpoints of the sweeps is already inferred as the
type that the cast asserted, so ty reports the cast as redundant. mypy
and pyright do not need it either.
The multidimensional spectrum parameter is added to a DummyInstrument
at runtime, so the start, stop and number of points of its setpoints
are not typed. ty infers the dtype of the expected setpoints, which are
built from these with np.repeat and np.tile, as generic[object] rather
than as unknown, and so finds no overload of assert_allclose that
accepts them.
Since ty 0.0.103 a nested generic class that is accessed through an
instance is specialized with the defaults of its type parameters, so
self._DelegateCache is a type[_DelegateCache[Any, InstrumentBase | None]]
that cannot be subscripted. Accessed through the class that defines it,
it is still the generic class. Nothing overrides _DelegateCache, so this
is the same class at runtime.
These tests call the deprecated override argument of
set_interdependencies, set attributes on a fake gclib module, return a
value from an instrument __init__, read a snapshot column that is not
part of RunOverviewDict, set the upper cutoff of an SR560 to DC, pass
an integer as the measurement mode of a B1517A and read the deprecated
TParameter from instrument_base on purpose. They are already suppressed
for pyright or mypy.
ty checks the code for the oldest supported Python version, so it also
checks the import of backports.zstd that is used before Python 3.14.
That package is only installed on those versions, so the import cannot
be resolved when ty runs on Python 3.14 or newer. Allow only that
module to be unresolved, rather than ignoring every unresolved import
in the file.
ty replaces the declared type of the converters with the type it infers
for the OrderedDict call, a union that includes the bound get method of
the inner dict, which it then fails to call. Passing the type arguments
to OrderedDict gives it the intended type, which also makes the
annotation redundant.
The set method of a parameter is now typed with the data type of the
parameter. These tests pass values of other types to it on purpose,
either to check that they are rejected or that values accepted by a
value mapping still work, and are already suppressed for mypy. The
fixture that overrides set does so on purpose too, since that is
rejected at runtime, which is what the test that uses it checks.
The sample count and timer of the Keysight 344xxA are annotated as
float | str, since they can also be set to the MIN, MAX and DEF
keywords. Their values are always parsed as numbers when read, so
convert them to int and float before computing the time of each
sample, which makes the arithmetic type check.
Add ty to the test extra and run it next to mypy and pyright. ty
understands Jupyter notebooks, which the other two do not, so this also
covers the example notebooks in docs. The scipy stubs are added to the
test extra for the notebooks that use scipy, and the paths to check are
configured in pyproject.toml.
Notes on how mypy, pyright and ty read each other's suppression
comments, with the test cases used to establish that. They are kept in
a single commit so that they are easy to drop before merging.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant