Repository: rsagroup/rsatoolbox

Issue:
Type hints
Should we (gradually) introduce type annotations? In recent python versions you can do:

```
def sum(a: int, b:int): -> int
    return a + b
```

and a tool such as _mypy_ or _pylance_ will check your code for violations while you're typing, often 
pointing out bugs based on expectations of what another component will do.
My proposal is that from henceforth, contributors who want to, may add such annotations.


Discussion:

Patch:
diff --git a/.bandit b/.bandit
deleted file mode 100644
index 6f9debfa..00000000
--- a/.bandit
+++ /dev/null
@@ -1,2 +0,0 @@
-[bandit]
-skips: B403, 301
diff --git a/.pylintrc b/.pylintrc
deleted file mode 100644
index 702f9e47..00000000
--- a/.pylintrc
+++ /dev/null
@@ -1,597 +0,0 @@
-[MASTER]
-
-# A comma-separated list of package or module names from where C extensions may
-# be loaded. Extensions are loading into the active Python interpreter and may
-# run arbitrary code.
-extension-pkg-whitelist=
-
-# Specify a score threshold to be exceeded before program exits with error.
-fail-under=10.0
-
-# Add files or directories to the blacklist. They should be base names, not
-# paths.
-ignore=CVS
-
-# Add files or directories matching the regex patterns to the blacklist. The
-# regex matches against base names, not paths.
-ignore-patterns=
-
-# Python code to execute, usually for sys.path manipulation such as
-# pygtk.require().
-#init-hook=
-
-# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
-# number of processors available to use.
-jobs=1
-
-# Control the amount of potential inferred values when inferring a single
-# object. This can help the performance when dealing with large functions or
-# complex, nested conditions.
-limit-inference-results=100
-
-# List of plugins (as comma separated values of python module names) to load,
-# usually to register additional checkers.
-load-plugins=
-
-# Pickle collected data for later comparisons.
-persistent=yes
-
-# When enabled, pylint would attempt to guess common misconfiguration and emit
-# user-friendly hints instead of false-positive error messages.
-suggestion-mode=yes
-
-# Allow loading of arbitrary C extensions. Extensions are imported into the
-# active Python interpreter and may run arbitrary code.
-unsafe-load-any-extension=no
-
-
-[MESSAGES CONTROL]
-
-# Only show warnings with the listed confidence levels. Leave empty to show
-# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED.
-confidence=
-
-# Disable the message, report, category or checker with the given id(s). You
-# can either give multiple identifiers separated by comma (,) or put this
-# option multiple times (only on the command line, not in the configuration
-# file where it should appear only once). You can also use "--disable=all" to
-# disable everything first and then reenable specific checks. For example, if
-# you want to run only the similarities checker, you can use "--disable=all
-# --enable=similarities". If you want to run only the classes checker, but have
-# no Warning level messages displayed, use "--disable=all --enable=classes
-# --disable=W".
-disable=print-statement,
-        parameter-unpacking,
-        unpacking-in-except,
-        old-raise-syntax,
-        backtick,
-        long-suffix,
-        old-ne-operator,
-        old-octal-literal,
-        import-star-module-level,
-        non-ascii-bytes-literal,
-        raw-checker-failed,
-        bad-inline-option,
-        locally-disabled,
-        file-ignored,
-        suppressed-message,
-        useless-suppression,
-        deprecated-pragma,
-        use-symbolic-message-instead,
-        apply-builtin,
-        basestring-builtin,
-        buffer-builtin,
-        cmp-builtin,
-        coerce-builtin,
-        execfile-builtin,
-        file-builtin,
-        long-builtin,
-        raw_input-builtin,
-        reduce-builtin,
-        standarderror-builtin,
-        unicode-builtin,
-        xrange-builtin,
-        coerce-method,
-        delslice-method,
-        getslice-method,
-        setslice-method,
-        no-absolute-import,
-        old-division,
-        dict-iter-method,
-        dict-view-method,
-        next-method-called,
-        metaclass-assignment,
-        indexing-exception,
-        raising-string,
-        reload-builtin,
-        oct-method,
-        hex-method,
-        nonzero-method,
-        cmp-method,
-        input-builtin,
-        round-builtin,
-        intern-builtin,
-        unichr-builtin,
-        map-builtin-not-iterating,
-        zip-builtin-not-iterating,
-        range-builtin-not-iterating,
-        filter-builtin-not-iterating,
-        using-cmp-argument,
-        eq-without-hash,
-        div-method,
-        idiv-method,
-        rdiv-method,
-        exception-message-attribute,
-        invalid-str-codec,
-        sys-max-int,
-        bad-python3-import,
-        deprecated-string-function,
-        deprecated-str-translate-call,
-        deprecated-itertools-function,
-        deprecated-types-field,
-        next-method-defined,
-        dict-items-not-iterating,
-        dict-keys-not-iterating,
-        dict-values-not-iterating,
-        deprecated-operator-function,
-        deprecated-urllib-function,
-        xreadlines-attribute,
-        deprecated-sys-function,
-        exception-escape,
-        comprehension-escape,
-        no-self-use,
-        use-dict-literal,
-        use-list-literal, ## can cause issues with references being reused
-        too-few-public-methods ## also flagged on enum's
-        superfluous-parens ## can be good for readability
-
-# Enable the message, report, category or checker with the given id(s). You can
-# either give multiple identifier separated by comma (,) or put this option
-# multiple time (only on the command line, not in the configuration file where
-# it should appear only once). See also the "--disable" option for examples.
-enable=c-extension-no-member
-
-
-[REPORTS]
-
-# Python expression which should return a score less than or equal to 10. You
-# have access to the variables 'error', 'warning', 'refactor', and 'convention'
-# which contain the number of messages in each category, as well as 'statement'
-# which is the total number of statements analyzed. This score is used by the
-# global evaluation report (RP0004).
-evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
-
-# Template used to display messages. This is a python new-style format string
-# used to format the message information. See doc for all details.
-#msg-template=
-
-# Set the output format. Available formats are text, parseable, colorized, json
-# and msvs (visual studio). You can also give a reporter class, e.g.
-# mypackage.mymodule.MyReporterClass.
-output-format=text
-
-# Tells whether to display a full report or only the messages.
-reports=no
-
-# Activate the evaluation score.
-score=yes
-
-
-[REFACTORING]
-
-# Maximum number of nested blocks for function / method body
-max-nested-blocks=5
-
-# Complete name of functions that never returns. When checking for
-# inconsistent-return-statements if a never returning function is called then
-# it will be considered as an explicit return statement and no message will be
-# printed.
-never-returning-functions=sys.exit
-
-
-[SPELLING]
-
-# Limits count of emitted suggestions for spelling mistakes.
-max-spelling-suggestions=4
-
-# Spelling dictionary name. Available dictionaries: none. To make it work,
-# install the python-enchant package.
-spelling-dict=
-
-# List of comma separated words that should not be checked.
-spelling-ignore-words=
-
-# A path to a file that contains the private dictionary; one word per line.
-spelling-private-dict-file=
-
-# Tells whether to store unknown words to the private dictionary (see the
-# --spelling-private-dict-file option) instead of raising a message.
-spelling-store-unknown-words=no
-
-
-[VARIABLES]
-
-# List of additional names supposed to be defined in builtins. Remember that
-# you should avoid defining new builtins when possible.
-additional-builtins=
-
-# Tells whether unused global variables should be treated as a violation.
-allow-global-unused-variables=yes
-
-# List of strings which can identify a callback function by name. A callback
-# name must start or end with one of those strings.
-callbacks=cb_,
-          _cb
-
-# A regular expression matching the name of dummy variables (i.e. expected to
-# not be used).
-dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
-
-# Argument names that match this expression will be ignored. Default to name
-# with leading underscore.
-ignored-argument-names=_.*|^ignored_|^unused_
-
-# Tells whether we should check for unused import in __init__ files.
-init-import=no
-
-# List of qualified module names which can have objects that can redefine
-# builtins.
-redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
-
-
-[FORMAT]
-
-# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
-expected-line-ending-format=
-
-# Regexp for a line that is allowed to be longer than the limit.
-ignore-long-lines=^\s*(# )?<?https?://\S+>?$
-
-# Number of spaces of indent required inside a hanging or continued line.
-indent-after-paren=4
-
-# String used as indentation unit. This is usually "    " (4 spaces) or "\t" (1
-# tab).
-indent-string='    '
-
-# Maximum number of characters on a single line.
-max-line-length=100
-
-# Maximum number of lines in a module.
-max-module-lines=1000
-
-# Allow the body of a class to be on the same line as the declaration if body
-# contains single statement.
-single-line-class-stmt=no
-
-# Allow the body of an if to be on the same line as the test if there is no
-# else.
-single-line-if-stmt=no
-
-
-[TYPECHECK]
-
-# List of decorators that produce context managers, such as
-# contextlib.contextmanager. Add to this list to register other decorators that
-# produce valid context managers.
-contextmanager-decorators=contextlib.contextmanager
-
-# List of members which are set dynamically and missed by pylint inference
-# system, and so shouldn't trigger E1101 when accessed. Python regular
-# expressions are accepted.
-generated-members=
-
-# Tells whether missing members accessed in mixin class should be ignored. A
-# mixin class is detected if its name ends with "mixin" (case insensitive).
-ignore-mixin-members=yes
-
-# Tells whether to warn about missing members when the owner of the attribute
-# is inferred to be None.
-ignore-none=yes
-
-# This flag controls whether pylint should warn about no-member and similar
-# checks whenever an opaque object is returned when inferring. The inference
-# can return multiple potential results while evaluating a Python object, but
-# some branches might not be evaluated, which results in partial inference. In
-# that case, it might be useful to still emit no-member and other checks for
-# the rest of the inferred objects.
-ignore-on-opaque-inference=yes
-
-# List of class names for which member attributes should not be checked (useful
-# for classes with dynamically set attributes). This supports the use of
-# qualified names.
-ignored-classes=optparse.Values,thread._local,_thread._local
-
-# List of module names for which member attributes should not be checked
-# (useful for modules/projects where namespaces are manipulated during runtime
-# and thus existing member attributes cannot be deduced by static analysis). It
-# supports qualified module names, as well as Unix pattern matching.
-ignored-modules=
-
-# Show a hint with possible names when a member name was not found. The aspect
-# of finding the hint is based on edit distance.
-missing-member-hint=yes
-
-# The minimum edit distance a name should have in order to be considered a
-# similar match for a missing member name.
-missing-member-hint-distance=1
-
-# The total number of similar names that should be taken in consideration when
-# showing a hint for a missing member.
-missing-member-max-choices=1
-
-# List of decorators that change the signature of a decorated function.
-signature-mutators=
-
-
-[SIMILARITIES]
-
-# Ignore comments when computing similarities.
-ignore-comments=yes
-
-# Ignore docstrings when computing similarities.
-ignore-docstrings=yes
-
-# Ignore imports when computing similarities.
-ignore-imports=no
-
-# Minimum lines number of a similarity.
-min-similarity-lines=4
-
-
-[MISCELLANEOUS]
-
-# List of note tags to take in consideration, separated by a comma.
-notes=FIXME,
-      XXX,
-      TODO
-
-# Regular expression of note tags to take in consideration.
-#notes-rgx=
-
-
-[BASIC]
-
-# Naming style matching correct argument names.
-argument-naming-style=snake_case
-
-# Regular expression matching correct argument names. Overrides argument-
-# naming-style.
-#argument-rgx=
-
-# Naming style matching correct attribute names.
-attr-naming-style=snake_case
-
-# Regular expression matching correct attribute names. Overrides attr-naming-
-# style.
-#attr-rgx=
-
-# Bad variable names which should always be refused, separated by a comma.
-bad-names=foo,
-          bar,
-          baz,
-          toto,
-          tutu,
-          tata
-
-# Bad variable names regexes, separated by a comma. If names match any regex,
-# they will always be refused
-bad-names-rgxs=
-
-# Naming style matching correct class attribute names.
-class-attribute-naming-style=any
-
-# Regular expression matching correct class attribute names. Overrides class-
-# attribute-naming-style.
-#class-attribute-rgx=
-
-# Naming style matching correct class names.
-class-naming-style=PascalCase
-
-# Regular expression matching correct class names. Overrides class-naming-
-# style.
-#class-rgx=
-
-# Naming style matching correct constant names.
-const-naming-style=UPPER_CASE
-
-# Regular expression matching correct constant names. Overrides const-naming-
-# style.
-#const-rgx=
-
-# Minimum line length for functions/classes that require docstrings, shorter
-# ones are exempt.
-docstring-min-length=-1
-
-# Naming style matching correct function names.
-function-naming-style=snake_case
-
-# Regular expression matching correct function names. Overrides function-
-# naming-style.
-#function-rgx=
-
-# Good variable names which should always be accepted, separated by a comma.
-good-names=i,
-           j,
-           k,
-           ex,
-           Run,
-           by,
-           t,
-           _,
-           df,
-           ds
-
-# Good variable names regexes, separated by a comma. If names match any regex,
-# they will always be accepted
-good-names-rgxs=
-
-# Include a hint for the correct naming format with invalid-name.
-include-naming-hint=no
-
-# Naming style matching correct inline iteration names.
-inlinevar-naming-style=any
-
-# Regular expression matching correct inline iteration names. Overrides
-# inlinevar-naming-style.
-#inlinevar-rgx=
-
-# Naming style matching correct method names.
-method-naming-style=snake_case
-
-# Regular expression matching correct method names. Overrides method-naming-
-# style.
-#method-rgx=
-
-# Naming style matching correct module names.
-module-naming-style=snake_case
-
-# Regular expression matching correct module names. Overrides module-naming-
-# style.
-#module-rgx=
-
-# Colon-delimited sets of names that determine each other's naming style when
-# the name regexes allow several styles.
-name-group=
-
-# Regular expression which should only match function or class names that do
-# not require a docstring.
-no-docstring-rgx=^_
-
-# List of decorators that produce properties, such as abc.abstractproperty. Add
-# to this list to register other decorators that produce valid properties.
-# These decorators are taken in consideration only for invalid-name.
-property-classes=abc.abstractproperty
-
-# Naming style matching correct variable names.
-variable-naming-style=snake_case
-
-# Regular expression matching correct variable names. Overrides variable-
-# naming-style.
-#variable-rgx=
-
-
-[LOGGING]
-
-# The type of string formatting that logging methods do. `old` means using %
-# formatting, `new` is for `{}` formatting.
-logging-format-style=old
-
-# Logging modules to check that the string format arguments are in logging
-# function parameter format.
-logging-modules=logging
-
-
-[STRING]
-
-# This flag controls whether inconsistent-quotes generates a warning when the
-# character used as a quote delimiter is used inconsistently within a module.
-check-quote-consistency=no
-
-# This flag controls whether the implicit-str-concat should generate a warning
-# on implicit string concatenation in sequences defined over several lines.
-check-str-concat-over-line-jumps=no
-
-
-[DESIGN]
-
-# Maximum number of arguments for function / method.
-max-args=5
-
-# Maximum number of attributes for a class (see R0902).
-max-attributes=30
-
-# Maximum number of boolean expressions in an if statement (see R0916).
-max-bool-expr=5
-
-# Maximum number of branch for function / method body.
-max-branches=12
-
-# Maximum number of locals for function / method body.
-max-locals=15
-
-# Maximum number of parents for a class (see R0901).
-max-parents=7
-
-# Maximum number of public methods for a class (see R0904).
-max-public-methods=20
-
-# Maximum number of return / yield for function / method body.
-max-returns=6
-
-# Maximum number of statements in function / method body.
-max-statements=50
-
-# Minimum number of public methods for a class (see R0903).
-min-public-methods=2
-
-
-[IMPORTS]
-
-# List of modules that can be imported at any level, not just the top level
-# one.
-allow-any-import-level=
-
-# Allow wildcard imports from modules that define __all__.
-allow-wildcard-with-all=no
-
-# Analyse import fallback blocks. This can be used to support both Python 2 and
-# 3 compatible code, which means that the block might have code that exists
-# only in one or another interpreter, leading to false positives when analysed.
-analyse-fallback-blocks=no
-
-# Deprecated modules which should not be used, separated by a comma.
-deprecated-modules=optparse,tkinter.tix
-
-# Create a graph of external dependencies in the given file (report RP0402 must
-# not be disabled).
-ext-import-graph=
-
-# Create a graph of every (i.e. internal and external) dependencies in the
-# given file (report RP0402 must not be disabled).
-import-graph=
-
-# Create a graph of internal dependencies in the given file (report RP0402 must
-# not be disabled).
-int-import-graph=
-
-# Force import order to recognize a module as part of the standard
-# compatibility libraries.
-known-standard-library=
-
-# Force import order to recognize a module as part of a third party library.
-known-third-party=enchant
-
-# Couples of modules and preferred modules, separated by a comma.
-preferred-modules=
-
-
-[CLASSES]
-
-# List of method names used to declare (i.e. assign) instance attributes.
-defining-attr-methods=__init__,
-                      __new__,
-                      setUp,
-                      __post_init__
-
-# List of member names, which should be excluded from the protected access
-# warning.
-exclude-protected=_asdict,
-                  _fields,
-                  _replace,
-                  _source,
-                  _make
-
-# List of valid names for the first argument in a class method.
-valid-classmethod-first-arg=cls
-
-# List of valid names for the first argument in a metaclass class method.
-valid-metaclass-classmethod-first-arg=cls
-
-
-[EXCEPTIONS]
-
-# Exceptions that will emit a warning when being caught. Defaults to
-# "BaseException, Exception".
-overgeneral-exceptions=BaseException,
-                       Exception
diff --git a/MANIFEST.in b/MANIFEST.in
index 2190162a..f5b9c522 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -1,4 +1,5 @@
 recursive-include src/rsatoolbox *.mplstyle
+include src/rsatoolbox/py.typed
 include requirements.txt
 include tests/requirements.txt
 recursive-exclude *.yml
diff --git a/codecov.yml b/codecov.yml
deleted file mode 100644
index b79b7ef5..00000000
--- a/codecov.yml
+++ /dev/null
@@ -1,15 +0,0 @@
-codecov:
-  require_ci_to_pass: yes
-
-coverage:
-  precision: 2
-  round: down
-  range: "80...100"
-  status:
-    project:
-      default:
-        target: auto
-        threshold: 0%
-
-ignore:
-  - "tests"
\ No newline at end of file
diff --git a/devops/gha.py b/devops/gha.py
new file mode 100644
index 00000000..f1886008
--- /dev/null
+++ b/devops/gha.py
@@ -0,0 +1,48 @@
+#!/usr/bin/env python3
+"""Helper functions for Github Actions
+"""
+from typing import Tuple
+import sys
+import os
+ENV_VAR_NAME = 'DEVOPS_ASST_API_ARGS'
+
+
+def parse_github_args() -> Tuple[str, str, str]:
+    assert len(sys.argv) == (1+3), 'Expected three input arguments'
+    run_id = sys.argv[1] # github.run_id
+    job_id = sys.argv[2] # github.job
+    sha = sys.argv[3]    # github.event.pull_request.head.sha
+    return run_id, job_id, sha
+
+
+def count_log_issues(fpath: str) -> int:
+    with open(fpath) as fhandle:
+        lines = fhandle.readlines()
+    if len(lines) < 2:
+        return 0
+    lines.reverse()
+    for line in lines:
+        if line.startswith('Found '):
+            return int(line.split()[1])
+        elif 'pyright' in fpath:
+            return int(line.split()[0])
+    else:
+        raise ValueError('[devops.gha] Could not find summary line')
+
+
+def set_github_summary_api_envs(accept: bool, description: str, summary: str, context: str) -> None:
+    run_id, job_id, sha = parse_github_args()
+    target_url = (f'https://github.com/rsagroup/rsatoolbox/actions/runs/{ run_id }' 
+                  f'/attempts/1#summary-{ job_id }')
+    state = 'success' if accept else 'failure' # error, failure, pending, or success
+    api_url = f'/repos/rsagroup/rsatoolbox/statuses/{ sha }'
+    cmd = (f'--method POST {api_url} -f "state={state}" ' +
+           f'-f "target_url={target_url}" -f "description={description}" -f "context={context}"')
+
+    if 'GITHUB_STEP_SUMMARY' in os.environ:
+        with open(os.environ['GITHUB_STEP_SUMMARY'], 'a') as fhandle:
+            fhandle.write(summary)
+
+    if 'GITHUB_ENV' in os.environ:
+        with open(os.environ['GITHUB_ENV'], 'a') as fhandle:
+            fhandle.write(f'{ENV_VAR_NAME}={cmd}')
diff --git a/devops/style_assistant.py b/devops/style_assistant.py
new file mode 100644
index 00000000..f3db3301
--- /dev/null
+++ b/devops/style_assistant.py
@@ -0,0 +1,28 @@
+#!/usr/bin/env python3
+"""Helper for processing the Ruff log output
+"""
+from gha import count_log_issues, set_github_summary_api_envs
+
+THRESHOLD = 0  # How many errors are allowed
+CONTEXT = 'Ruff'
+
+n = count_log_issues('ruff.log')
+accept = n <= THRESHOLD
+
+summary_issues = """
+### Ruff: {} issues found :construction:
+
+See individual errors below under *Annotations*, or 
+see them inline at the *Files Changed* tab of the Pull Request.
+
+You can also install ruff (`pip install ruff`) on your machine
+and then run `ruff check` locally.
+"""
+
+summary_ok = """
+### Ruff: No issues found :sparkles:
+"""
+
+summary = summary_ok if accept else summary_issues.format(n)
+description = 'No issues found' if accept else f'Found {n} issues'
+set_github_summary_api_envs(accept, description, summary, CONTEXT)
diff --git a/devops/typing_assistant.py b/devops/typing_assistant.py
new file mode 100644
index 00000000..b3b139ef
--- /dev/null
+++ b/devops/typing_assistant.py
@@ -0,0 +1,34 @@
+#!/usr/bin/env python3
+"""Helper for processing the Pyright log output
+"""
+from gha import count_log_issues, set_github_summary_api_envs
+
+THRESHOLD = 0  # How many errors are allowed
+CONTEXT = 'Pyright'
+
+old_n = count_log_issues('pyright_main.log')
+new_n = count_log_issues('pyright_pr.log')
+diff_n = new_n - old_n
+accept = diff_n <= THRESHOLD
+
+summary_issues = """
+### Pyright: {} new issues found :construction:
+
+Try to annotate your new code with type annotations. 
+You can check for typing issues with the python plugin for your IDE,
+or on the terminal by installing pyright (`pip install pyright`) 
+on your machine and then run `pyright` locally.
+"""
+
+summary_ok = """
+### Pyright: No new issues found :fireworks:
+
+{} fewer issues compared to the main branch!
+"""
+
+summary = summary_ok.format(diff_n) if accept else summary_issues.format(diff_n)
+description = f'Found {abs(diff_n)} fewer issues compared to main'
+if diff_n > 0:
+    description = f'Found {diff_n} more issues compared to main'
+set_github_summary_api_envs(accept, description, summary, CONTEXT)
+
diff --git a/pyproject.toml b/pyproject.toml
index f1628424..1384202e 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -65,3 +65,15 @@ test-requires = "pytest"
 test-command = "pytest {project}/tests"
 before-test = "pip install -r tests/requirements.txt"
 skip = ["*-win32", "*-manylinux_i686", "*-musllinux_*", "pp*"]
+
+[tool.pyright]
+include = ["src"]
+exclude = []
+ignore = []
+defineConstant = { DEBUG = true }
+stubPath = ""
+reportMissingImports = false
+pythonVersion = "3.11"
+executionEnvironments = [
+  { root = "src" }
+]
diff --git a/requirements.txt b/requirements.txt
index d2199b6a..86a57728 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -3,7 +3,7 @@ scipy>=1.10.1
 scikit-learn
 scikit-image
 pandas
-matplotlib
+matplotlib!=3.9.1
 h5py
 tqdm
 joblib
diff --git a/ruff.toml b/ruff.toml
new file mode 100644
index 00000000..9238de0f
--- /dev/null
+++ b/ruff.toml
@@ -0,0 +1,12 @@
+line-length = 100
+extend-exclude = ["docs/source/conf.py"]
+
+[format]
+quote-style = "single"
+docstring-code-format = true
+
+[lint.per-file-ignores]
+"__init__.py" = ["F401"]
+
+[lint.pydocstyle]
+convention = "google"
diff --git a/setup.cfg b/setup.cfg
deleted file mode 100644
index 17754ab4..00000000
--- a/setup.cfg
+++ /dev/null
@@ -1,4 +0,0 @@
-[pep8]  # deprecated in pycodestyle but codeclimate still uses this.
-count = False
-statistics = True
-ignore = E121
\ No newline at end of file
diff --git a/src/rsatoolbox/data/base.py b/src/rsatoolbox/data/base.py
index d0a25d20..3b9a887c 100644
--- a/src/rsatoolbox/data/base.py
+++ b/src/rsatoolbox/data/base.py
@@ -78,7 +78,7 @@ class DatasetBase:
                 f'channel_descriptors: \n{string_channel_desc}\n'
                 )
 
-    def __eq__(self, other: DatasetBase) -> bool:
+    def __eq__(self, other: object) -> bool:
         """Equality check, to be implemented in the specific
         Dataset class
 
@@ -92,7 +92,10 @@ class DatasetBase:
         Returns:
             bool: Never returns
         """
-        raise NotImplementedError()
+        if isinstance(other, DatasetBase):
+            raise NotImplementedError()
+        else:
+            return False
 
     def copy(self) -> DatasetBase:
         """Copy Dataset
diff --git a/src/rsatoolbox/data/dataset.py b/src/rsatoolbox/data/dataset.py
index 5d9cde92..0b7dc2e5 100644
--- a/src/rsatoolbox/data/dataset.py
+++ b/src/rsatoolbox/data/dataset.py
@@ -32,7 +32,7 @@ class Dataset(DatasetBase):
     It contains one data set - or multiple data sets with the same structure
     """
 
-    def __eq__(self, other: Dataset) -> bool:
+    def __eq__(self, other: object) -> bool:
         """Test for equality
         This magic method gets called when you compare two
         Datasets objects: `ds1 == ds2`.
@@ -45,13 +45,14 @@ class Dataset(DatasetBase):
         Returns:
             bool: True if the objects' properties are equal
         """
-        return all([
-            isinstance(other, Dataset),
-            np.all(self.measurements == other.measurements),
-            self.descriptors == other.descriptors,
-            desc_eq(self.obs_descriptors, other.obs_descriptors),
-            desc_eq(self.channel_descriptors, other.channel_descriptors),
-        ])
+        if isinstance(other, Dataset):
+            return all([
+                np.all(self.measurements == other.measurements),
+                self.descriptors == other.descriptors,
+                desc_eq(self.obs_descriptors, other.obs_descriptors),
+                desc_eq(self.channel_descriptors, other.channel_descriptors),
+            ])
+        return False
 
     def copy(self) -> Dataset:
         """Return a copy of this object, with all properties
@@ -414,15 +415,16 @@ class TemporalDataset(Dataset):
         self.channel_descriptors = parse_input_descriptor(channel_descriptors)
         self.time_descriptors = parse_input_descriptor(time_descriptors)
 
-    def __eq__(self, other: TemporalDataset) -> bool:
-        return all([
-            isinstance(other, TemporalDataset),
-            np.all(self.measurements == other.measurements),
-            self.descriptors == other.descriptors,
-            desc_eq(self.obs_descriptors, other.obs_descriptors),
-            desc_eq(self.channel_descriptors, other.channel_descriptors),
-            desc_eq(self.time_descriptors, other.time_descriptors)
-        ])
+    def __eq__(self, other: object) -> bool:
+        if isinstance(other, TemporalDataset):
+            return all([
+                np.all(self.measurements == other.measurements),
+                self.descriptors == other.descriptors,
+                desc_eq(self.obs_descriptors, other.obs_descriptors),
+                desc_eq(self.channel_descriptors, other.channel_descriptors),
+                desc_eq(self.time_descriptors, other.time_descriptors)
+            ])
+        return False
 
     def __str__(self):
         """
@@ -789,7 +791,7 @@ class TemporalDataset(Dataset):
 
         """
         warn('Deprecated: [TemporalDataset.convert_to_dataset()]. Replace by '
-            '[TemporalDataset.time_as_observations()]', DeprecationWarning)
+             '[TemporalDataset.time_as_observations()]', DeprecationWarning)
         return self.time_as_observations(by)
 
     def to_dict(self):
diff --git a/src/rsatoolbox/py.typed b/src/rsatoolbox/py.typed
new file mode 100644
index 00000000..e69de29b
diff --git a/src/rsatoolbox/rdm/combine.py b/src/rsatoolbox/rdm/combine.py
index 0aac44f3..c2a04110 100644
--- a/src/rsatoolbox/rdm/combine.py
+++ b/src/rsatoolbox/rdm/combine.py
@@ -131,7 +131,7 @@ def rescale(rdms, method: str = 'evidence', threshold=1e-8):
     Args:
         method (str, optional): One of 'evidence', 'setsize' or
             'simple'. Defaults to 'evidence'.
-        threshold (float): Stop iterating when the sum of squares 
+        threshold (float): Stop iterating when the sum of squares
             difference between iterations is smaller than this value.
             A smaller value means more iterations, but the algorithm
             may not always converge.
@@ -152,7 +152,7 @@ def rescale(rdms, method: str = 'evidence', threshold=1e-8):
     )
 
 
-def _mean(vectors: ndarray, weights: ndarray = None) -> ndarray:
+def _mean(vectors: ndarray, weights: Optional[ndarray] = None) -> ndarray:
     """Weighted mean of RDM vectors, ignores nans
 
     See :meth:`rsatoolbox.rdm.rdms.RDMs.mean`
diff --git a/src/rsatoolbox/rdm/rdms.py b/src/rsatoolbox/rdm/rdms.py
index 447ed480..f28855cb 100644
--- a/src/rsatoolbox/rdm/rdms.py
+++ b/src/rsatoolbox/rdm/rdms.py
@@ -105,7 +105,7 @@ class RDMs:
                 f'pattern_descriptors = \n{self.pattern_descriptors}\n'
                 )
 
-    def __eq__(self, other: RDMs) -> bool:
+    def __eq__(self, other: object) -> bool:
         """Test for equality
         This magic method gets called when you compare two
         RDMs objects: `rdms1 == rdms2`.
@@ -119,13 +119,14 @@ class RDMs:
         Returns:
             bool: True if equal
         """
-        return all([
-            isinstance(other, RDMs),
-            np.all(self.dissimilarities == other.dissimilarities),
-            self.descriptors == other.descriptors,
-            desc_eq(self.rdm_descriptors, other.rdm_descriptors),
-            desc_eq(self.pattern_descriptors, other.pattern_descriptors),
-        ])
+        if isinstance(other, RDMs):
+            return all([
+                np.all(self.dissimilarities == other.dissimilarities),
+                self.descriptors == other.descriptors,
+                desc_eq(self.rdm_descriptors, other.rdm_descriptors),
+                desc_eq(self.pattern_descriptors, other.pattern_descriptors),
+            ])
+        return False
 
     def __str__(self):
         """
@@ -428,7 +429,7 @@ class RDMs:
         """Reorder the patterns by sorting a descriptor
 
         Args:
-            reindex (bool): whether to reset the 'index' descriptor 
+            reindex (bool): whether to reset the 'index' descriptor
                 following sorting
 
         Pass keyword arguments that correspond to descriptors,
diff --git a/src/rsatoolbox/rdm/transform.py b/src/rsatoolbox/rdm/transform.py
index 8ec1e926..7c50c9ca 100644
--- a/src/rsatoolbox/rdm/transform.py
+++ b/src/rsatoolbox/rdm/transform.py
@@ -11,7 +11,7 @@ from scipy.spatial.distance import squareform
 from .rdms import RDMs
 
 
-def rank_transform(rdms: RDMs, method='average') -> RDMs:
+def rank_transform(rdms: RDMs, method: str = 'average') -> RDMs:
     """ applies a rank_transform and generates a new RDMs object
     This assigns a rank to each dissimilarity estimate in the RDM,
     deals with rank ties and saves ranks as new dissimilarity estimates.
@@ -46,7 +46,7 @@ def rank_transform(rdms: RDMs, method='average') -> RDMs:
     )
 
 
-def sqrt_transform(rdms):
+def sqrt_transform(rdms: RDMs) -> RDMs:
     """ applies a square root transform and generates a new RDMs object
     This sets values blow 0 to 0 and takes a square root of each entry.
     It also adds a sqrt to the dissimilarity_measure entry.
@@ -61,7 +61,9 @@ def sqrt_transform(rdms):
     dissimilarities = rdms.get_vectors()
     dissimilarities[dissimilarities < 0] = 0
     dissimilarities = np.sqrt(dissimilarities)
-    if rdms.dissimilarity_measure == 'squared euclidean':
+    if rdms.dissimilarity_measure is None:
+        dissimilarity_measure = 'sqrt of unknown measure'
+    elif rdms.dissimilarity_measure == 'squared euclidean':
         dissimilarity_measure = 'euclidean'
     elif rdms.dissimilarity_measure == 'squared mahalanobis':
         dissimilarity_measure = 'mahalanobis'
@@ -75,7 +77,7 @@ def sqrt_transform(rdms):
     return rdms_new
 
 
-def positive_transform(rdms):
+def positive_transform(rdms: RDMs) -> RDMs:
     """ sets all negative entries in an RDM to zero and returns a new RDMs
 
     Args:
@@ -95,7 +97,7 @@ def positive_transform(rdms):
     return rdms_new
 
 
-def transform(rdms, fun):
+def transform(rdms: RDMs, fun) -> RDMs:
     """ applies an arbitray function ``fun`` to the dissimilarities and
     returns a new RDMs object.
 
@@ -108,7 +110,10 @@ def transform(rdms, fun):
     """
     dissimilarities = rdms.get_vectors()
     dissimilarities = fun(dissimilarities)
-    meas = 'transformed ' + rdms.dissimilarity_measure
+    if rdms.dissimilarity_measure is None:
+        meas = 'transformed unknown measure'
+    else:
+        meas = 'transformed ' + rdms.dissimilarity_measure
     rdms_new = RDMs(dissimilarities,
                     dissimilarity_measure=meas,
                     descriptors=deepcopy(rdms.descriptors),
@@ -118,13 +123,13 @@ def transform(rdms, fun):
 
 
 def minmax_transform(rdms: RDMs) -> RDMs:
-    '''applies a minmax transform to the dissimilarities and returns a new 
+    '''applies a minmax transform to the dissimilarities and returns a new
     RDMs object.
-    
+
     Args:
         rdms(RDMs): RDMs object
-    
-    Returns:    
+
+    Returns:
         rdms_new(RDMs): RDMs object with minmax transformed dissimilarities
     '''
     dissimilarities = rdms.get_vectors()
@@ -132,7 +137,10 @@ def minmax_transform(rdms: RDMs) -> RDMs:
         d_max = dissimilarities[i].max()
         d_min = dissimilarities[i].min()
         dissimilarities[i] = (dissimilarities[i] - d_min) / (d_max - d_min)
-    meas = 'minmax transformed ' + rdms.dissimilarity_measure
+    if rdms.dissimilarity_measure is None:
+        meas = 'minmax transformed unknown measure'
+    else:
+        meas = 'minmax transformed ' + rdms.dissimilarity_measure
     rdms_new = RDMs(dissimilarities,
                     dissimilarity_measure=meas,
                     descriptors=deepcopy(rdms.descriptors),
@@ -141,30 +149,33 @@ def minmax_transform(rdms: RDMs) -> RDMs:
     return rdms_new
 
 
-def geotopological_transform(rdms: RDMs, l: float, u: float) -> RDMs:
-    '''applies a geo-topological transform to the dissimilarities and returns 
-    a new RDMs object. 
-    
-    Reference: Lin, B., & Kriegeskorte, N. (2023). The Topology and Geometry 
+def geotopological_transform(rdms: RDMs, low: float, up: float) -> RDMs:
+    '''applies a geo-topological transform to the dissimilarities and returns
+    a new RDMs object.
+
+    Reference: Lin, B., & Kriegeskorte, N. (2023). The Topology and Geometry
     of Neural Representations. arXiv preprint arXiv:2309.11028.
-    
+
     Args:
         rdms(RDMs): RDMs object
-        l(float): lower quantile
-        u(float): upper quantile
-    
-    Returns:    
+        low(float): lower quantile
+        up(float): upper quantile
+
+    Returns:
         rdms_new(RDMs): RDMs object with geotopological transformed dissimilarities
     '''
     dissimilarities = rdms.get_vectors()
-    gt_min = np.quantile(dissimilarities, l)
-    gt_max = np.quantile(dissimilarities, u)
+    gt_min = np.quantile(dissimilarities, low)
+    gt_max = np.quantile(dissimilarities, up)
     dissimilarities[dissimilarities < gt_min] = 0
     dissimilarities[(dissimilarities >= gt_min) & (dissimilarities <= gt_max)] = (
         dissimilarities[(dissimilarities >= gt_min) & (dissimilarities <= gt_max)] - gt_min
     ) / (gt_max - gt_min)
     dissimilarities[dissimilarities > gt_max] = 1
-    meas = 'geo-topological transformed ' + rdms.dissimilarity_measure
+    if rdms.dissimilarity_measure is None:
+        meas = 'geo-topological transformed unknown measure'
+    else:
+        meas = 'geo-topological transformed ' + rdms.dissimilarity_measure
     rdms_new = RDMs(dissimilarities,
                     dissimilarity_measure=meas,
                     descriptors=deepcopy(rdms.descriptors),
@@ -174,16 +185,16 @@ def geotopological_transform(rdms: RDMs, l: float, u: float) -> RDMs:
 
 
 def geodesic_transform(rdms: RDMs) -> RDMs:
-    '''applies a geodesic transform to the dissimilarities and returns a 
-    new RDMs object. 
-    
-    Reference: Lin, B., & Kriegeskorte, N. (2023). The Topology and Geometry 
+    '''applies a geodesic transform to the dissimilarities and returns a
+    new RDMs object.
+
+    Reference: Lin, B., & Kriegeskorte, N. (2023). The Topology and Geometry
     of Neural Representations. arXiv preprint arXiv:2309.11028.
-    
+
     Args:
         rdms(RDMs): RDMs object
-    
-    Returns:    
+
+    Returns:
         rdms_new(RDMs): RDMs object with geodesic transformed dissimilarities
     '''
     dissimilarities = minmax_transform(rdms).get_vectors()
@@ -195,7 +206,10 @@ def geodesic_transform(rdms: RDMs) -> RDMs:
         le_ids = list(e[:2] for e in long_edges)
         G.remove_edges_from(le_ids)
         dissimilarities[i] = squareform(np.array(nx.floyd_warshall_numpy(G)))
-    meas = 'geodesic transformed ' + rdms.dissimilarity_measure
+    if rdms.dissimilarity_measure is None:
+        meas = 'geodesic transformed unknown measure'
+    else:
+        meas = 'geodesic transformed ' + rdms.dissimilarity_measure
     rdms_new = RDMs(dissimilarities,
                     dissimilarity_measure=meas,
                     descriptors=deepcopy(rdms.descriptors),
diff --git a/src/rsatoolbox/util/matrix.py b/src/rsatoolbox/util/matrix.py
index 01b3f714..7893600c 100644
--- a/src/rsatoolbox/util/matrix.py
+++ b/src/rsatoolbox/util/matrix.py
@@ -4,10 +4,9 @@
 Collection of different utility Matrices
 """
 
-from typing import List
-
+from typing import List, Optional
 import numpy as np
-from scipy.sparse import coo_matrix, csr_matrix
+from scipy.sparse import coo_matrix, csr_matrix, spmatrix
 
 
 def indicator(index_vector, positive=False):
@@ -67,7 +66,7 @@ def pairwise_contrast(index_vector):
     return indicator_matrix
 
 
-def pairwise_contrast_sparse(index_vector):
+def pairwise_contrast_sparse(index_vector) -> csr_matrix:
     """ Contrast matrix with one row per unqiue pairwise contrast
 
     Args:
@@ -105,7 +104,7 @@ def pairwise_contrast_sparse(index_vector):
             n_row = n_row + 1
     indicator_matrix = coo_matrix((dat, (idx_i, idx_j)),
                                   shape=(cols, rows))
-    return indicator_matrix.asformat("csr")
+    return indicator_matrix.asformat("csr")  # pyright: ignore reportReturnType
 
 
 def centering(size):
@@ -152,7 +151,7 @@ def row_col_indicator_g(n_cond):
         row_indicator (numpy.ndarray): n_cond (n_cond-1)/2+n_cond * n_cond
         col_indicator (numpy.ndarray): n_cond (n_cond-1)/2+n_cond * n_cond
     """
-    n_elem = int(n_cond * (n_cond - 1) / 2)+n_cond  # Number of elements in G
+    n_elem = int(n_cond * (n_cond - 1) / 2) + n_cond  # Number of elements in G
     row_i = np.zeros((n_elem, n_cond))
     col_i = np.zeros((n_elem, n_cond))
     _row_col_indicator(row_i, col_i, n_cond)
@@ -161,7 +160,15 @@ def row_col_indicator_g(n_cond):
     return (row_i, col_i)
 
 
-def get_v(n_cond, sigma_k):
+def run() -> spmatrix:
+    a = csr_matrix(np.eye(3))
+    b = csr_matrix(np.eye(3))
+    c = a @ b
+    c = c.multiply(3.0)
+    return c
+
+
+def get_v(n_cond: int, sigma_k: Optional[spmatrix]) -> spmatrix:
     """ get the rdm covariance from sigma_k """
     # calculate Xi
     c_mat = pairwise_contrast_sparse(np.arange(n_cond))
diff --git a/src/rsatoolbox/util/rdm_utils.py b/src/rsatoolbox/util/rdm_utils.py
index 8164c752..d0d8b62f 100644
--- a/src/rsatoolbox/util/rdm_utils.py
+++ b/src/rsatoolbox/util/rdm_utils.py
@@ -101,7 +101,7 @@ def _get_n_from_length(n):
     return int(np.ceil(np.sqrt(n * 2)))
 
 
-def add_pattern_index(rdms, pattern_descriptor):
+def add_pattern_index(rdms: RDMs, pattern_descriptor):
     """
     adds index if pattern_descriptor is None
 
@@ -174,7 +174,7 @@ def _extract_triu_(X):
     return X[mask]
 
 
-def category_condition_idxs(rdms,
+def category_condition_idxs(rdms: RDMs,
                             category_selector: Union[str, List[int]]
                             ) -> Dict[str, List[int]]:
     """
@@ -196,10 +196,6 @@ def category_condition_idxs(rdms,
 
     @author: caiw
     """
-
-    from rsatoolbox.rdm import RDMs
-    rdms: RDMs
-
     _msg_arg_category_selector = (
         "Argument category_selector must be a string specifying a "
         "pattern_descriptor or a list of ints indicating RDM conditions."
diff --git a/src/rsatoolbox/vis/model_map.py b/src/rsatoolbox/vis/model_map.py
index 0ec164c7..4d6cb345 100644
--- a/src/rsatoolbox/vis/model_map.py
+++ b/src/rsatoolbox/vis/model_map.py
@@ -339,7 +339,7 @@ def plot_model_map(locs2d, significant, model_significant, model_below_lower_bou
     ns_col = [0, 0, 0, 0.15]  # color for non-significance cords and rays
 
     # prepare axes for map
-    l, b, w, h = 0.15, 0.15, 0.85, 0.85
+    l, b, w, h = 0.15, 0.15, 0.85, 0.85  # noqa: E741
     ax = plt.axes((l, b, w, h))
     r_max = np.max(np.sqrt(np.sum(np.array(locs2d)**2, axis=1)))
     clearance_fac = 1.08  # factor by which the maximum radius is multiplied
diff --git a/src/rsatoolbox/vis/model_plot.py b/src/rsatoolbox/vis/model_plot.py
index e8e2d136..3c9a42d1 100644
--- a/src/rsatoolbox/vis/model_plot.py
+++ b/src/rsatoolbox/vis/model_plot.py
@@ -279,7 +279,7 @@ def plot_model_comparison(result, sort=False, colors=None,
 
     # Prepare axes for bars and pairwise comparisons
     fs, fs2 = 18, 14  # axis label font sizes
-    l, b, w, h = 0.15, 0.15, 0.8, 0.8
+    l, b, w, h = 0.15, 0.15, 0.8, 0.8  # noqa: E741
     fig = plt.figure(figsize=(12.5, 10))
     if test_pair_comparisons is True:
         test_pair_comparisons = 'arrows'
diff --git a/src/rsatoolbox/vis/rdm_plot.py b/src/rsatoolbox/vis/rdm_plot.py
index 3d81bd58..943b8ae4 100755
--- a/src/rsatoolbox/vis/rdm_plot.py
+++ b/src/rsatoolbox/vis/rdm_plot.py
@@ -114,12 +114,12 @@ def show_rdm(
             default), 1.1 means pad 10%, .9 means overlap 10% etc.
         linewidth (float): Width of connecting lines from icon labels (if used) to axis
             margin.  The default is 0.5 - set to 0. to disable the lines.
-        overlay ((str, str) or NDArray): RDM descriptor name-value tuple, 
+        overlay ((str, str) or NDArray): RDM descriptor name-value tuple,
             or vector (one value per pair) which indicates whether to highlight the given cells
         overlay_color (str): Color to use to highlight the pairs in the overlay argument.
             Use RGBA to specify transparency. Default is 50% opaque green.
-        contour ((str, str) or NDArray): RDM descriptor name-value tuple, 
-            or vector (one value per pair) which indicates whether to add a border 
+        contour ((str, str) or NDArray): RDM descriptor name-value tuple,
+            or vector (one value per pair) which indicates whether to add a border
             to the given cells
         contour_color (str): Color to use for a border around pairs in the contour argument.
             Use RGBA to specify transparency. Default is red.
@@ -144,10 +144,11 @@ def show_rdm(
     )
     return _plot_multi_rdm(conf)
 
+
 def _plot_multi_rdm(conf: MultiRdmPlot) -> Tuple[Figure, NDArray, Dict[int, Dict[str, Any]]]:
     # A dictionary of figure element handles
     handles = dict()
-    handles[-1] = dict() # fig level handles
+    handles[-1] = dict()  # fig level handles
     # create a list of (row index, column index) tuples
     rc_tuples = list(itertools.product(range(conf.n_row), range(conf.n_column)))
     # number of empty panels at the top
@@ -164,7 +165,7 @@ def _plot_multi_rdm(conf: MultiRdmPlot) -> Tuple[Figure, NDArray, Dict[int, Dict
         p = 0
         for p, (r, c) in enumerate(rc_tuples):
             handles[p] = dict()
-            rdm_index = p - n_empty ## rdm index
+            rdm_index = p - n_empty  # rdm index
             if rdm_index < 0:
                 ax_array[r, c].set_visible(False)
                 continue
@@ -205,7 +206,7 @@ def _adjust_colorbar_pos(cb: Colorbar, parent: Axes) -> None:
     """
     # key challenge is to obtain a similarly-sized colorbar to the 'panel' case
     # BUT positioned centered on the reserved subplot axes
-    #parent = ax_array[-1, -1]
+    # parent = ax_array[-1, -1]
     cbax_parent_orgpos = parent.get_position(original=True)
     # use last instance of 'image' (should all be yoked at this point)
     cbax_pos = cb.ax.get_position()
@@ -281,11 +282,11 @@ def show_rdm_panel(
             argument.
         vmax (float): Maximum intensity for colorbar mapping. matplotlib imshow
             argument.
-        overlay ((str, str) or NDArray): RDM descriptor name-value tuple, or vector 
+        overlay ((str, str) or NDArray): RDM descriptor name-value tuple, or vector
             (one value per pair) which indicates whether to highlight the given cells
         overlay_color (str): Color to use to highlight the pairs in the overlay argument.
             Use RGBA to specify transparency. Default is 50% opaque green.
-        contour ((str, str) or NDArray): RDM descriptor name-value tuple, or vector 
+        contour ((str, str) or NDArray): RDM descriptor name-value tuple, or vector
             (one value per pair) which indicates whether to add a border to the given cells
         contour_color (str): Color to use for a border around pairs in the contour argument.
             Use RGBA to specify transparency. Default is red.
@@ -293,9 +294,11 @@ def show_rdm_panel(
     Returns:
         matplotlib.image.AxesImage: Matplotlib handle.
     """
-    conf = SingleRdmPlot.from_show_rdm_panel_args(rdms, cmap, nanmask,
+    conf = SingleRdmPlot.from_show_rdm_panel_args(
+        rdms, cmap, nanmask,
         rdm_descriptor, gridlines, vmin, vmax, overlay, overlay_color,
-        overlay_symmetry, contour, contour_color, contour_symmetry)
+        overlay_symmetry, contour, contour_color, contour_symmetry
+    )
     return _show_rdm_panel(conf, ax or plt.gca())
 
 
@@ -312,7 +315,8 @@ def _show_rdm_panel(conf: SingleRdmPlot, ax: Axes) -> AxesImage:
     rdmat = conf.rdms.get_matrices()[0, :, :]
     if np.any(conf.nanmask):
         rdmat[conf.nanmask] = np.nan
-    image = ax.imshow(rdmat, cmap=conf.cmap, vmin=conf.vmin, vmax=conf.vmax,
+    image = ax.imshow(
+        rdmat, cmap=conf.cmap, vmin=conf.vmin, vmax=conf.vmax,
         interpolation='none')
     _overlay(conf, ax)
     _contour(conf, ax)
@@ -396,10 +400,10 @@ def _contour_coords(mask: NDArray, offset: float) -> Iterator[Tuple[float, float
     mask_t = mask.T
     mask_idx = np.where(mask_t)
     sides = [
-        (( 0, -1), (0, 0, 1, 0)), # top
-        (( 1,  0), (1, 0, 1, 1)), # right
-        (( 0,  1), (1, 1, 0, 1)), # bottom
-        ((-1,  0), (0, 1, 0, 0)), # left
+        ((0, -1), (0, 0, 1, 0)),  # top
+        ((1,  0), (1, 0, 1, 1)),  # right
+        ((0,  1), (1, 1, 0, 1)),  # bottom
+        ((-1,  0), (0, 1, 0, 0)),  # left
     ]
     for x, y in np.vstack(mask_idx).T:
         for neighbor, edge in sides:
@@ -431,11 +435,11 @@ def _add_descriptor_labels(which_axis: Axis, ax: Axes, conf: MultiRdmPlot) -> Li
     if which_axis == Axis.X:
         icon_method = "x_tick_label"
         axis = ax.xaxis
-        horizontalalignment="center"
+        horizontalalignment = "center"
     else:
         icon_method = "y_tick_label"
         axis = ax.yaxis
-        horizontalalignment="right"
+        horizontalalignment = "right"
     descriptor_arr = np.asarray(conf.rdms.pattern_descriptors[conf.pattern_descriptor])
     if isinstance(descriptor_arr[0], vis.Icon):
         return _add_descriptor_icons(
@@ -499,8 +503,8 @@ def _add_descriptor_icons(
     descriptor_arr: ArrayLike,
     icon_method: str,
     n_cond: int,
-    ax: Axes = None,
-    num_pattern_groups: int = None,
+    ax: Optional[Axes] = None,
+    num_pattern_groups: Optional[int] = None,
     icon_spacing: float = 1.0,
     linewidth: float = 0.5,
 ) -> list:
@@ -523,8 +527,6 @@ def _add_descriptor_icons(
         list: Tick label handles.
     """
     # annotated labels with Icon
-    #import pdb
-    #pdb.set_trace()
     n_to_fit = np.ceil(n_cond / num_pattern_groups)
     # work out sizing of icons
     im_max_pix = 20.
@@ -540,7 +542,7 @@ def _add_descriptor_icons(
     # from proportion of original size to figure pixels
     offset = (im_max_pix / icon_spacing) * size
     label_handles = []
-    for group_ind in range(num_pattern_groups - 1, -1, -1): ## e.g. 2->1->0 for npg = 3
+    for group_ind in range(num_pattern_groups - 1, -1, -1):  # e.g. 2->1->0 for npg = 3
         position = offset * 0.2 + offset * group_ind
         ticks = np.arange(group_ind, n_cond, num_pattern_groups)
         label_handles.append(
@@ -627,8 +629,8 @@ class MultiRdmPlot:
         conf.n_panel = rdm.n_rdm + int(show_colorbar == "figure")
         if show_colorbar == "figure":
             rdmat = rdm.get_matrices()
-            vmin = vmin or rdmat[:, (conf.nanmask == False)].min()
-            vmax = vmax or rdmat[:, (conf.nanmask == False)].max()
+            vmin = vmin or rdmat[:, ~conf.nanmask].min()
+            vmax = vmax or rdmat[:, ~conf.nanmask].max()
         conf.vmin = vmin
         conf.vmax = vmax
         conf.n_row, conf.n_column = cls.determine_rows_cols_panels(
@@ -682,7 +684,7 @@ class MultiRdmPlot:
             n_row: Optional[int],
             n_column: Optional[int],
             n_panel: int
-        ) -> Tuple[int, int]:
+    ) -> Tuple[int, int]:
         """Choose the number of rows and columns of panels
         """
         if (n_column is None) and (n_row is None):
@@ -698,7 +700,7 @@ class MultiRdmPlot:
             cls,
             nanmask: NDArray | str | None,
             rdms: RDMs,
-        ) -> NDArray:
+    ) -> NDArray:
         """Interpret user's choice of nanmask
         """
         if nanmask is None:
@@ -773,7 +775,7 @@ class MultiRdmPlot:
         self.overlay_symmetry = Symmetry.BOTH
         self.contour = np.zeros(n_pairs)
         self.contour_color = 'red'
-        self.contour_symmetry= Symmetry.BOTH
+        self.contour_symmetry = Symmetry.BOTH
 
     def addOverlay(self, mask: ArrayOrRdmDescriptor, color: str, triangles: Symmetry):
         self.overlay = self.interpret_rdm_arg(mask, self.rdms)
diff --git a/src/rsatoolbox/vis/timecourse.py b/src/rsatoolbox/vis/timecourse.py
index f1757fd5..431b034f 100644
--- a/src/rsatoolbox/vis/timecourse.py
+++ b/src/rsatoolbox/vis/timecourse.py
@@ -17,13 +17,13 @@ if TYPE_CHECKING:
 def plot_timecourse(
         rdms_data: RDMs,
         descriptor: str,
-        n_t_display:int = 20,
+        n_t_display: int = 20,
         fig_width: Optional[int] = None,
         timecourse_plot_rel_height: Optional[int] = None,
         time_formatted: Optional[List[str]] = None,
         colored_conditions: Optional[list] = None,
         plot_individual_dissimilarities: Optional[bool] = None,
-    ) -> Tuple[Figure, List[Axes]]:
+) -> Tuple[Figure, List[Axes]]:
     """ plots the RDM movie for a given descriptor
 
     Args:
@@ -75,11 +75,11 @@ def plot_timecourse(
     # figure layout
     fig = plt.figure(
         constrained_layout=True,
-        figsize=(base_size*n_t_display,base_size*timecourse_plot_rel_height)
+        figsize=(base_size * n_t_display, base_size * timecourse_plot_rel_height)
     )
     gs = fig.add_gridspec(timecourse_plot_rel_height+1, n_t_display)
-    tc_ax = fig.add_subplot(gs[:-1,:])
-    rdm_axes = [fig.add_subplot(gs[-1,i]) for i in range(n_t_display)]
+    tc_ax = fig.add_subplot(gs[:-1, :])
+    rdm_axes = [fig.add_subplot(gs[-1, i]) for i in range(n_t_display)]
 
     # plot dissimilarity timecourses
     dissimilarities_mean = np.zeros((rdms_data.dissimilarities.shape[1], len(unique_time)))
@@ -88,10 +88,10 @@ def plot_timecourse(
 
     def _plot_mean_dissimilarities(labels=False):
         for i, (pairwise_name, idx) in enumerate(color_index.items()):
-            mn = np.mean(dissimilarities_mean[idx, :],axis=0)
+            mn = np.mean(dissimilarities_mean[idx, :], axis=0)
             n = np.sqrt(dissimilarities_mean.shape[0])
             # se is over dissimilarities, not over subjects
-            se = np.std(dissimilarities_mean[idx, :],axis=0)/n
+            se = np.std(dissimilarities_mean[idx, :], axis=0)/n
             tc_ax.fill_between(unique_time, mn-se, mn+se, color=colors[i], alpha=.3)
             label = pairwise_name if labels else None
             tc_ax.plot(unique_time, mn, color=colors[i], linewidth=2, label=label)
@@ -115,22 +115,22 @@ def plot_timecourse(
 
     yl = tc_ax.get_ylim()
     for t in unique_time[t_display_idx]:
-        tc_ax.plot([t,t], yl, linestyle=':', color='b', alpha=0.3)
+        tc_ax.plot([t, t], yl, linestyle=':', color='b', alpha=0.3)
     tc_ax.set_ylabel(f'Dissimilarity\n({rdms_data.dissimilarity_measure})')
     tc_ax.set_xticks(unique_time)
     tc_ax.set_xticklabels([
-        time_formatted[idx]  if idx in t_display_idx else '' for idx in range(len(unique_time))
+        time_formatted[idx] if idx in t_display_idx else '' for idx in range(len(unique_time))
     ])
     dt = np.diff(unique_time[t_display_idx])[0]
-    tc_ax.set_xlim(unique_time[t_display_idx[0]]-dt/2, unique_time[t_display_idx[-1]]+dt/2)
+    tc_ax.set_xlim(unique_time[t_display_idx[0]] - dt / 2, unique_time[t_display_idx[-1]]+dt/2)
 
     tc_ax.legend()
 
     # display (selected) rdms
     vmax = np.std(rdms_data.dissimilarities) * 2
     for i, (tidx, a) in enumerate(zip(t_display_idx, rdm_axes)):
-        mean_dissim = np.mean(rdms_data.subset('time', unique_time[tidx]).get_matrices(),axis=0)
-        a.imshow(mean_dissim, vmin=0, vmax=vmax)
+        mean_dissim = np.mean(rdms_data.subset('time', unique_time[tidx]).get_matrices(), axis=0)
+        a.imshow(mean_dissim, vmin=0, vmax=vmax)  # pyright: ignore reportArgumentType
         a.set_title(f'{np.round(unique_time[tidx]*1000,2):0.0f} ms')
         a.set_yticklabels([])
         a.set_yticks([])
@@ -150,7 +150,7 @@ def _map_colors(
         colored_conditions: Optional[list],
         plot_individual_dissimilarities: Optional[bool],
         rdms: RDMs
-    ) -> Tuple[bool, Dict[str, NDArray]]:
+) -> Tuple[bool, Dict[str, NDArray]]:
     n_dissimilarity_elements = rdms.dissimilarities.shape[1]
     # color mapping from colored conditions
     if colored_conditions is not None:
@@ -161,11 +161,11 @@ def _map_colors(
         pairwise_conds_unique = np.unique(pairwise_conds)
         color_index = {}
         for x in pairwise_conds_unique:
-            if len(list(x))==2:
+            if len(list(x)) == 2:
                 key = f'{list(x)[0]} vs {list(x)[1]}'
             else:
                 key = f'{list(x)[0]} vs {list(x)[0]}'
-            color_index[key] = pairwise_conds==x
+            color_index[key] = pairwise_conds == x
     else:
         color_index = {'': np.array([True]*n_dissimilarity_elements)}
         plot_individual_dissimilarities = True


Test patch:
diff --git a/.github/workflows/testbuild.yml b/.github/workflows/testbuild.yml
index 9332790f..1ecd3068 100644
--- a/.github/workflows/testbuild.yml
+++ b/.github/workflows/testbuild.yml
@@ -34,6 +34,79 @@ jobs:
     - name: Unit tests
       run: pytest
 
+  style:
+    runs-on: ubuntu-22.04
+    permissions:
+        statuses: write
+    env:
+        GH_TOKEN: ${{ github.token }}
+    steps:
+    - uses: actions/checkout@v4
+      with:
+        fetch-depth: 0
+    - uses: actions/setup-python@v5
+      with:
+        python-version: '3.11'
+    - name: Install dependencies
+      run: pip install ruff
+    - name: Ruff output to file
+      run: ruff check -ne -o ruff.log --output-format concise
+    - name: Ruff output as annotations
+      run: echo "$(ruff check -e --output-format github)"
+    - name: Process Ruff output
+      run: python devops/style_assistant.py ${{ github.run_id }} ${{ github.job }} ${{ github.event.pull_request.head.sha }}
+    - name: Report status
+      run: gh api ${{ env.DEVOPS_ASST_API_ARGS }}
+
+
+  typing:
+    runs-on: ubuntu-22.04
+    permissions:
+        statuses: write
+    env:
+        GH_TOKEN: ${{ github.token }}
+    steps:
+    - uses: actions/setup-python@v5
+      with:
+        python-version: '3.11'
+    - name: Python Version
+      run: python --version
+    - name: Update Pip
+      run: python -m pip install --upgrade pip
+    - name: Install dependencies
+      run: pip install build setuptools pandas-stubs types-tqdm pyright
+    - uses: actions/checkout@v4
+      with:
+        ref: main
+        fetch-depth: 0
+    - name: Build package
+      run: python -m build --sdist
+    - name: Install rsatoolbox 
+      run: pip install dist/*
+    - name: Pyright (on main)
+      continue-on-error: true
+      run: pyright > pyright_main.log
+    - name: Uninstall rsatoolbox 
+      run: pip uninstall -y rsatoolbox
+    - name: Remove builds
+      run: rm dist/*
+    - uses: actions/checkout@v4
+      with:
+        clean: false
+        fetch-depth: 0
+    - name: Build package
+      run: python -m build --sdist
+    - name: Install rsatoolbox 
+      run: pip install dist/*
+    - name: Pyright (on PR)
+      continue-on-error: true
+      run: pyright > pyright_pr.log
+    - name: Process Pyright output
+      run: python devops/typing_assistant.py ${{ github.run_id }} ${{ github.job }} ${{ github.event.pull_request.head.sha }}
+    - name: Report status
+      run: gh api ${{ env.DEVOPS_ASST_API_ARGS }}
+
+
   source:
     needs: tests
     runs-on: ${{ matrix.os }}
diff --git a/tests/test_data.py b/tests/test_data.py
index 5e66d9fc..137327e7 100644
--- a/tests/test_data.py
+++ b/tests/test_data.py
@@ -596,7 +596,7 @@ class TestSave(unittest.TestCase):
                            )
         data_dict = data.to_dict()
         data_loaded = rsd.dataset_from_dict(data_dict)
-        assert type(data_loaded) == type(data)
+        assert type(data_loaded) is type(data)
         assert data_loaded.n_channel == data.n_channel
         assert np.all(data_loaded.obs_descriptors['conds'] == obs_des['conds'])
         assert np.all(data_loaded.channel_descriptors['rois']
@@ -633,7 +633,7 @@ class TestOESplit(unittest.TestCase):
     def test_oe_split(self):
         measurements = self.rng.random((4, 10))
         des = {'session': 0, 'subj': 0}
-        chn_des = {'rois': np.array([chr(l) for l in range(65, 75)])}
+        chn_des = {'rois': np.array([chr(i) for i in range(65, 75)])}
 
         self.full_data = rsd.Dataset(
             measurements=measurements,
@@ -684,7 +684,7 @@ class TestOESplit(unittest.TestCase):
     def test_odd_even_split_nested(self):
         measurements = self.rng.random((16, 10))
         des = {'session': 0, 'subj': 0}
-        chn_des = {'rois': np.array([chr(l) for l in range(65, 75)])}
+        chn_des = {'rois': np.array([chr(i) for i in range(65, 75)])}
         conds = np.array([str(i) for i in range(1, 5)])
         runs = np.array([i for i in range(1, 5)])
         self.full_data = rsd.Dataset(
diff --git a/tests/test_io_fmriprep.py b/tests/test_io_fmriprep.py
index bda04a3f..19ad229c 100644
--- a/tests/test_io_fmriprep.py
+++ b/tests/test_io_fmriprep.py
@@ -3,7 +3,8 @@
 from unittest import TestCase
 from unittest.mock import patch, Mock
 from numpy.testing import assert_array_equal
-import pandas, numpy
+import pandas
+import numpy
 
 
 class TestFindFmriprepRuns(TestCase):
diff --git a/tests/test_rdm.py b/tests/test_rdm.py
index 32601523..962137e6 100644
--- a/tests/test_rdm.py
+++ b/tests/test_rdm.py
@@ -311,7 +311,7 @@ class TestRDM(unittest.TestCase):
                         pattern_descriptors=pattern_des,
                         dissimilarity_measure=mes,
                         descriptors=des)
-        gt_rdm = geotopological_transform(rdms, l=0.2, u=0.8)
+        gt_rdm = geotopological_transform(rdms, low=0.2, up=0.8)
         self.assertEqual(gt_rdm.n_rdm, rdms.n_rdm)
         self.assertEqual(gt_rdm.n_cond, rdms.n_cond)