[go: nahoru, domu]

Skip to content

Commit

Permalink
update pre-comit (#698)
Browse files Browse the repository at this point in the history
  • Loading branch information
giovp committed Jun 4, 2023
1 parent 540ad9a commit 4530150
Show file tree
Hide file tree
Showing 38 changed files with 193 additions and 197 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ jobs:
python: [3.9, "3.10"]
os: [ubuntu-latest]
include:
- python: 3.8
os: macos-latest
- python: 3.9
os: macos-latest
- python: "3.10"
os: macos-latest
env:
OS: ${{ matrix.os }}
PYTHON: ${{ matrix.python }}
Expand Down
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ default_stages:
minimum_pre_commit_version: 2.9.3
repos:
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.2.0
rev: v1.3.0
hooks:
- id: mypy
additional_dependencies: [numpy, pandas, types-requests]
Expand Down Expand Up @@ -56,7 +56,7 @@ repos:
- id: blacken-docs
- repo: https://github.com/charliermarsh/ruff-pre-commit
# Ruff version.
rev: v0.0.265
rev: v0.0.270
hooks:
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
Expand Down
4 changes: 2 additions & 2 deletions docs/source/_ext/typed_returns.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ def _process_return(lines: Iterable[str]) -> Iterator[str]:
yield line


def _parse_returns_section(self: NumpyDocstring, section: str) -> List[str]:
def _parse_returns_section(self: NumpyDocstring, section: str) -> list[str]:
lines_raw = list(_process_return(self._dedent(self._consume_to_next_section())))
lines: List[str] = self._format_block(":returns: ", lines_raw)
lines: list[str] = self._format_block(":returns: ", lines_raw)
if lines and lines[-1]:
lines.append("")
return lines
Expand Down
2 changes: 1 addition & 1 deletion docs/source/installation.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Installation
============
Squidpy requires Python version >= 3.8 to run.
Squidpy requires Python version >= 9 to run.

PyPI
----
Expand Down
4 changes: 2 additions & 2 deletions docs/source/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def fetch_local(repo_path: Union[str, Path]) -> None:


class MaybeMiniGallery(MiniGallery):
def run(self) -> List[str]:
def run(self) -> list[str]:
config = self.state.document.settings.env.config
backreferences_dir = config.sphinx_gallery_conf["backreferences_dir"]
obj_list = self.arguments[0].split()
Expand All @@ -75,7 +75,7 @@ def run(self) -> List[str]:
return []


def _get_thumbnails(root: Union[str, Path]) -> Dict[str, str]:
def _get_thumbnails(root: Union[str, Path]) -> dict[str, str]:
res = {}
root = Path(root)
thumb_path = Path(__file__).parent.parent.parent / "docs" / "source"
Expand Down
4 changes: 1 addition & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -184,9 +184,7 @@ target-version = "py38"
"squidpy/pl/_interactive/_widgets.py"= ["D"]
".scripts/ci/download_data.py"= ["D","B"]
# "squidpy/*.py"= ["RST303"]
[tool.ruff.pyupgrade]
# Preserve types, even if a file imports `from __future__ import annotations`.
keep-runtime-typing = true

[tool.ruff.flake8-tidy-imports]
# Disallow all relative imports.
ban-relative-imports = "all"
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ omnipath @ git+https://github.com/saezlab/omnipath@master
pandas>=1.5.0
Pillow>=8.0.0
scanpy>=1.9.3
scikit-image>=0.19
scikit-image>=0.19,<=0.20 # due to https://github.com/scikit-image/scikit-image/issues/6850 breaks rescale ufunc
scikit-learn>=0.24.0
statsmodels>=0.12.0
tifffile!=2022.4.22 # https://github.com/scverse/squidpy/issues/526
Expand Down
1 change: 0 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@
"Operating System :: MacOS :: MacOS X",
"Typing :: Typed",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Environment :: Console",
Expand Down
7 changes: 2 additions & 5 deletions squidpy/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from importlib.metadata import version

from packaging.version import parse

from squidpy import datasets, gr, im, pl, read, tl
Expand All @@ -11,11 +13,6 @@
)
__version__ = "1.2.3"

try:
from importlib_metadata import version # Python < 3.8
except ImportError:
from importlib.metadata import version # Python = 3.8


try:
__full_version__ = parse(version(__name__))
Expand Down
16 changes: 8 additions & 8 deletions squidpy/_constants/_pkg_constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@ def __get__(self, obj: Any, owner: Any) -> str:
class Key:
class img:
@classmethod
def segment(cls, backend: Union[str, SegmentationBackend], layer_added: Optional[str] = None) -> str:
def segment(cls, backend: str | SegmentationBackend, layer_added: str | None = None) -> str:
return f"segmented_{SegmentationBackend(backend).s}" if layer_added is None else layer_added

@classmethod
def process(
cls, method: Union[str, Processing, Callable[[Any], Any]], img_id: str, layer_added: Optional[str] = None
cls, method: str | Processing | Callable[[Any], Any], img_id: str, layer_added: str | None = None
) -> str:
if layer_added is not None:
return layer_added
Expand Down Expand Up @@ -91,11 +91,11 @@ def size_key(cls) -> str:
return "spot_diameter_fullres"

@classmethod
def spatial_neighs(cls, value: Optional[str] = None) -> str:
def spatial_neighs(cls, value: str | None = None) -> str:
return f"{Key.obsm.spatial}_neighbors" if value is None else f"{value}_neighbors"

@classmethod
def ligrec(cls, cluster: str, value: Optional[str] = None) -> str:
def ligrec(cls, cluster: str, value: str | None = None) -> str:
return f"{cluster}_ligrec" if value is None else value

@classmethod
Expand Down Expand Up @@ -127,7 +127,7 @@ def spot_diameter(
cls,
adata: AnnData,
spatial_key: str,
library_id: Optional[str] = None,
library_id: str | None = None,
spot_diameter_key: str = "spot_diameter_fullres",
) -> float:
try:
Expand Down Expand Up @@ -174,7 +174,7 @@ def _sort_haystack(
adata: AnnData,
spatial_key: str,
library_id: Sequence[str] | str | None = None,
sub_key: Optional[str] = None,
sub_key: str | None = None,
) -> Sequence[str] | None:
if spatial_key not in adata.uns:
raise KeyError(f"Spatial key {spatial_key!r} not found in `adata.uns`.")
Expand All @@ -195,9 +195,9 @@ def _sort_haystack(

class obsp:
@classmethod
def spatial_dist(cls, value: Optional[str] = None) -> str:
def spatial_dist(cls, value: str | None = None) -> str:
return f"{Key.obsm.spatial}_distances" if value is None else f"{value}_distances"

@classmethod
def spatial_conn(cls, value: Optional[str] = None) -> str:
def spatial_conn(cls, value: str | None = None) -> str:
return f"{Key.obsm.spatial}_connectivities" if value is None else f"{value}_connectivities"
10 changes: 6 additions & 4 deletions squidpy/_constants/_utils.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from __future__ import annotations

from abc import ABC, ABCMeta
from enum import Enum, EnumMeta
from functools import wraps
from typing import Any, Callable, Mapping, Tuple, Type
from typing import Any, Callable, Mapping, Tuple


def _pretty_raise_enum(cls: Type["ModeEnum"], fun: Callable[..., Any]) -> Callable[..., Any]:
def _pretty_raise_enum(cls: type[ModeEnum], fun: Callable[..., Any]) -> Callable[..., Any]:
@wraps(fun)
def wrapper(*args: Any, **kwargs: Any) -> Any:
try:
Expand Down Expand Up @@ -49,8 +51,8 @@ class ABCEnumMeta(EnumMeta, ABCMeta):
"""Metaclass which injects."""

def __new__( # noqa: D102
cls, clsname: str, bases: Tuple[EnumMeta, ...], namespace: Mapping[str, Any]
) -> "ABCEnumMeta":
cls, clsname: str, bases: tuple[EnumMeta, ...], namespace: Mapping[str, Any]
) -> ABCEnumMeta:
res = super().__new__(cls, clsname, bases, namespace) # type: ignore[arg-type]
res.__new__ = _pretty_raise_enum(res, res.__new__) # type: ignore[method-assign,arg-type]
return res
Expand Down
2 changes: 1 addition & 1 deletion squidpy/datasets/_dataset.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ from anndata import AnnData
from squidpy.datasets._utils import PathLike

class Dataset(Protocol):
def __call__(self, path: Union[PathLike, None] = ..., **kwargs: Any) -> AnnData: ...
def __call__(self, path: PathLike | None = ..., **kwargs: Any) -> AnnData: ...

four_i: Dataset
imc: Dataset
Expand Down
2 changes: 1 addition & 1 deletion squidpy/datasets/_image.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ from squidpy.datasets._utils import PathLike
from squidpy.im._container import ImageContainer

class ImageDataset(Protocol):
def __call__(self, path: Union[PathLike, None] = ..., **kwargs: Any) -> ImageContainer: ...
def __call__(self, path: PathLike | None = ..., **kwargs: Any) -> ImageContainer: ...

visium_fluo_image_crop: ImageDataset
visium_hne_image_crop: ImageDataset
Expand Down
4 changes: 2 additions & 2 deletions squidpy/datasets/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class Metadata(ABC):

doc_header: Optional[str] = field(default=None, repr=False)
path: Optional[PathLike] = field(default=None, repr=False)
shape: Optional[Tuple[int, int]] = field(default=None, repr=False)
shape: Optional[tuple[int, int]] = field(default=None, repr=False)
library_id: Optional[Union[str, Sequence[str]]] = field(default=None, repr=False)

_DOC_FMT = ""
Expand All @@ -48,7 +48,7 @@ def _download(self, fpath: PathLike, backup_url: str, **kwargs: Any) -> Any:
def _create_signature(self) -> Signature:
pass

def _create_function(self, name: str, glob_ns: Dict[str, Any]) -> None:
def _create_function(self, name: str, glob_ns: dict[str, Any]) -> None:
if name in globals():
raise KeyError(f"Function name `{name}` is already present in `{sorted(globals().keys())}`.")

Expand Down
2 changes: 1 addition & 1 deletion squidpy/gr/_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ def spatial_neighbors(
)

if library_key is not None:
mats: List[Tuple[spmatrix, spmatrix]] = []
mats: list[tuple[spmatrix, spmatrix]] = []
ixs = [] # type: ignore[var-annotated]
for lib in libs:
ixs.extend(np.where(adata.obs[library_key] == lib)[0])
Expand Down
17 changes: 4 additions & 13 deletions squidpy/gr/_ligrec.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,7 @@
from functools import partial
from itertools import product
from types import MappingProxyType
from typing import (
TYPE_CHECKING,
Any,
Iterable,
Literal,
Mapping,
Sequence,
Tuple,
Union,
)
from typing import TYPE_CHECKING, Any, Iterable, Literal, Mapping, Sequence, Union

import numpy as np
import pandas as pd
Expand All @@ -40,9 +31,9 @@
__all__ = ["ligrec", "PermutationTest"]

StrSeq = Sequence[str]
SeqTuple = Sequence[Tuple[str, str]]
Interaction_t = Union[pd.DataFrame, Mapping[str, StrSeq], StrSeq, Tuple[StrSeq, StrSeq], SeqTuple]
Cluster_t = Union[StrSeq, Tuple[StrSeq, StrSeq], SeqTuple]
SeqTuple = Sequence[tuple[str, str]]
Interaction_t = Union[pd.DataFrame, Mapping[str, StrSeq], StrSeq, tuple[StrSeq, StrSeq], SeqTuple]
Cluster_t = Union[StrSeq, tuple[StrSeq, StrSeq], SeqTuple]

SOURCE = "source"
TARGET = "target"
Expand Down
6 changes: 3 additions & 3 deletions squidpy/gr/_ppatterns.py
Original file line number Diff line number Diff line change
Expand Up @@ -461,8 +461,8 @@ def _p_value_calc(
score: NDArrayA,
sims: NDArrayA | None,
weights: spmatrix | NDArrayA,
params: Dict[str, Any],
) -> Dict[str, Any]:
params: dict[str, Any],
) -> dict[str, Any]:
"""
Handle p-value calculation for spatial autocorrelation function.
Expand Down Expand Up @@ -515,7 +515,7 @@ def _p_value_calc(
return results


def _analytic_pval(score: NDArrayA, g: spmatrix | NDArrayA, params: Dict[str, Any]) -> tuple[NDArrayA, float]:
def _analytic_pval(score: NDArrayA, g: spmatrix | NDArrayA, params: dict[str, Any]) -> tuple[NDArrayA, float]:
"""
Analytic p-value computation.
Expand Down
7 changes: 6 additions & 1 deletion squidpy/im/_container.py
Original file line number Diff line number Diff line change
Expand Up @@ -578,7 +578,12 @@ def _post_process(
) -> xr.Dataset:
def _rescale(arr: xr.DataArray) -> xr.DataArray:
scaling_fn = partial(
rescale, scale=[scale, scale, 1], preserve_range=True, order=1, channel_axis=-1, cval=cval
rescale,
preserve_range=True,
scale=[scale, scale, 1],
order=1,
channel_axis=-1,
cval=cval,
)
dtype = arr.dtype

Expand Down
4 changes: 2 additions & 2 deletions squidpy/im/_feature_mixin.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from squidpy.gr._utils import _assert_non_empty_sequence
from squidpy.im._coords import _NULL_PADDING, CropCoords

Feature_t = Dict[str, Any]
Feature_t = dict[str, Any]
Channel_t = Union[int, Sequence[int]]


Expand Down Expand Up @@ -378,7 +378,7 @@ def convert_to_full_image_coordinates(x: NDArrayA, y: NDArrayA) -> NDArrayA:
else:
channels = ()

features: Dict[str, Any] = {}
features: dict[str, Any] = {}
label_arr = self[label_layer].sel(z=library_id)
label_arr_0 = label_arr[..., 0].values
# calculate features that do not depend on the intensity image
Expand Down
2 changes: 1 addition & 1 deletion squidpy/pl/_color_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def _maybe_set_colors(

def _get_palette(
adata: AnnData,
cluster_key: Optional[str],
cluster_key: str | None,
categories: Sequence[Any],
palette: Palette_t = None,
alpha: float = 1.0,
Expand Down
10 changes: 5 additions & 5 deletions squidpy/pl/_interactive/_widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,20 +301,20 @@ def onCmapChanged(self, value: str) -> None:
self._colorbar.cmap = self._create_colormap(value)
self._colorbar._colorbar._update()

def setClim(self, value: Tuple[float, float]) -> None:
def setClim(self, value: tuple[float, float]) -> None:
if value == self._clim:
return

self._clim = value
self.climChanged.emit(*value)

def getClim(self) -> Tuple[float, float]:
def getClim(self) -> tuple[float, float]:
return self._clim

def getOclim(self) -> Tuple[float, float]:
def getOclim(self) -> tuple[float, float]:
return self._oclim

def setOclim(self, value: Tuple[float, float]) -> None:
def setOclim(self, value: tuple[float, float]) -> None:
# original color limit used for 0-1 normalization
self._oclim = value

Expand Down Expand Up @@ -354,7 +354,7 @@ def __init__(self, *args: Any, layer: Points, colorbar: CBarWidget, **kwargs: An

self.valueChanged.connect(self._onValueChange)

def _onValueChange(self, percentile: Tuple[float, float]) -> None:
def _onValueChange(self, percentile: tuple[float, float]) -> None:
# TODO(michalk8): use constants
v = self._layer.metadata["data"]
clipped = np.clip(v, *np.percentile(v, percentile))
Expand Down
Loading

0 comments on commit 4530150

Please sign in to comment.