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

Update version of pyupgrade #397

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ repos:
hooks:
- id: pyupgrade
args:
- --py36-plus
- --py39-plus

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
Expand Down
14 changes: 7 additions & 7 deletions ome_zarr/axes.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Axes class for validating and transforming axes
"""

from typing import Any, Dict, List, Union
from typing import Any, Union

from .format import CurrentFormat, Format

Expand All @@ -11,7 +11,7 @@
class Axes:
def __init__(
self,
axes: Union[List[str], List[Dict[str, str]]],
axes: Union[list[str], list[dict[str, str]]],
fmt: Format = CurrentFormat(),
) -> None:
"""
Expand Down Expand Up @@ -41,15 +41,15 @@ def validate(self) -> None:

def to_list(
self, fmt: Format = CurrentFormat()
) -> Union[List[str], List[Dict[str, str]]]:
) -> Union[list[str], list[dict[str, str]]]:
if fmt.version == "0.3":
return self._get_names()
return self.axes

@staticmethod
def _axes_to_dicts(
axes: Union[List[str], List[Dict[str, str]]]
) -> List[Dict[str, str]]:
axes: Union[list[str], list[dict[str, str]]]
) -> list[dict[str, str]]:
"""Returns a list of axis dicts with name and type"""
axes_dicts = []
for axis in axes:
Expand All @@ -74,7 +74,7 @@ def _validate_axes_types(self) -> None:
"Too many unknown axes types. 1 allowed, found: %s" % unknown_types
)

def _last_index(item: str, item_list: List[Any]) -> int:
def _last_index(item: str, item_list: list[Any]) -> int:
return max(loc for loc, val in enumerate(item_list) if val == item)

if "time" in axes_types and _last_index("time", axes_types) > 0:
Expand All @@ -88,7 +88,7 @@ def _last_index(item: str, item_list: List[Any]) -> int:
) > axes_types.index("space"):
raise ValueError("'space' axes must come after 'channel'")

def _get_names(self) -> List[str]:
def _get_names(self) -> list[str]:
"""Returns a list of axis names"""
axes_names = []
for axis in self.axes:
Expand Down
4 changes: 2 additions & 2 deletions ome_zarr/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import argparse
import logging
import sys
from typing import List, Union
from typing import Union

from .csv import csv_to_zarr
from .data import astronaut, coins, create_zarr
Expand Down Expand Up @@ -81,7 +81,7 @@ def csv_to_labels(args: argparse.Namespace) -> None:
csv_to_zarr(args.csv_path, args.csv_id, args.csv_keys, args.zarr_path, args.zarr_id)


def main(args: Union[List[str], None] = None) -> None:
def main(args: Union[list[str], None] = None) -> None:
"""Run appropriate function with argparse arguments, handling errors."""
parser = argparse.ArgumentParser()
parser.add_argument(
Expand Down
6 changes: 2 additions & 4 deletions ome_zarr/conversions.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
"""Simple conversion helpers."""

from typing import List


def int_to_rgba(v: int) -> List[float]:
def int_to_rgba(v: int) -> list[float]:
"""Get rgba (0-1) e.g. (1, 0.5, 0, 1) from integer.
>>> print(int_to_rgba(0))
[0.0, 0.0, 0.0, 0.0]
Expand All @@ -13,7 +11,7 @@ def int_to_rgba(v: int) -> List[float]:
return [x / 255 for x in v.to_bytes(4, signed=True, byteorder="big")]


def int_to_rgba_255(v: int) -> List[int]:
def int_to_rgba_255(v: int) -> list[int]:
"""Get rgba (0-255) from integer.
>>> print(int_to_rgba_255(0))
[0, 0, 0, 0]
Expand Down
8 changes: 4 additions & 4 deletions ome_zarr/csv.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import csv
import os
from typing import Dict, Union
from typing import Union

from zarr.convenience import open as zarr_open

Expand Down Expand Up @@ -50,7 +50,7 @@ def csv_to_zarr(

# Use #d to denote double etc.
# e.g. "area (pixels)#d,well_label#s,Width#l,Height#l"
cols_types_by_name: Dict[str, str] = {}
cols_types_by_name: dict[str, str] = {}
for col_name_type in csv_keys.split(","):
if "#" in col_name_type:
col_name, col_type = col_name_type.rsplit("#", 1)
Expand All @@ -62,7 +62,7 @@ def csv_to_zarr(
csv_columns = None
id_column = None

props_by_id: Dict[Union[str, int], Dict] = {}
props_by_id: dict[Union[str, int], dict] = {}

with open(csv_path, newline="") as csvfile:
row_reader = csv.reader(csvfile, delimiter=",")
Expand Down Expand Up @@ -90,7 +90,7 @@ def csv_to_zarr(


def dict_to_zarr(
props_to_add: Dict[Union[str, int], Dict], zarr_path: str, zarr_id: str
props_to_add: dict[Union[str, int], dict], zarr_path: str, zarr_id: str
) -> None:
"""
Add keys:values to the label properties of a ome-zarr Plate or Image.
Expand Down
6 changes: 3 additions & 3 deletions ome_zarr/dask_utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, Tuple
from typing import Any

import numpy as np
import skimage.transform
Expand All @@ -9,7 +9,7 @@


def resize(
image: da.Array, output_shape: Tuple[int, ...], *args: Any, **kwargs: Any
image: da.Array, output_shape: tuple[int, ...], *args: Any, **kwargs: Any
) -> da.Array:
r"""
Wrapped copy of "skimage.transform.resize"
Expand Down Expand Up @@ -62,7 +62,7 @@ def resize_block(image_block: da.Array, block_info: dict) -> da.Array:
return output.rechunk(image.chunksize).astype(image.dtype)


def downscale_nearest(image: da.Array, factors: Tuple[int, ...]) -> da.Array:
def downscale_nearest(image: da.Array, factors: tuple[int, ...]) -> da.Array:
"""
Primitive downscaling by integer factors using stepped slicing.
:type image: :class:`dask.array`
Expand Down
12 changes: 6 additions & 6 deletions ome_zarr/data.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Functions for generating synthetic data."""

from random import randrange
from typing import Callable, List, Optional, Tuple, Union
from typing import Callable, Optional, Union

import numpy as np
import zarr
Expand All @@ -20,7 +20,7 @@
CHANNEL_DIMENSION = 1


def coins() -> Tuple[List, List]:
def coins() -> tuple[list, list]:
"""Sample data from skimage."""
# Thanks to Juan
# https://gist.github.com/jni/62e07ddd135dbb107278bc04c0f9a8e7
Expand All @@ -36,7 +36,7 @@ def coins() -> Tuple[List, List]:
return pyramid, labels


def astronaut() -> Tuple[List, List]:
def astronaut() -> tuple[list, list]:
"""Sample data from skimage."""
scaler = Scaler()

Expand Down Expand Up @@ -85,7 +85,7 @@ def make_circle(h: int, w: int, value: int, target: np.ndarray) -> None:
target[mask] = value


def rgb_to_5d(pixels: np.ndarray) -> List:
def rgb_to_5d(pixels: np.ndarray) -> list:
"""Convert an RGB image into 5D image (t, c, z, y, x)."""
if len(pixels.shape) == 2:
stack = np.array([pixels])
Expand All @@ -101,10 +101,10 @@ def rgb_to_5d(pixels: np.ndarray) -> List:

def create_zarr(
zarr_directory: str,
method: Callable[..., Tuple[List, List]] = coins,
method: Callable[..., tuple[list, list]] = coins,
label_name: str = "coins",
fmt: Format = CurrentFormat(),
chunks: Optional[Union[Tuple, List]] = None,
chunks: Optional[Union[tuple, list]] = None,
) -> zarr.Group:
"""Generate a synthetic image pyramid with labels."""
pyramid, labels = method()
Expand Down
39 changes: 20 additions & 19 deletions ome_zarr/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

import logging
from abc import ABC, abstractmethod
from typing import Any, Dict, Iterator, List, Optional
from collections.abc import Iterator
from typing import Any, Optional

from zarr.storage import FSStore

Expand Down Expand Up @@ -91,29 +92,29 @@ def __eq__(self, other: object) -> bool:

@abstractmethod
def generate_well_dict(
self, well: str, rows: List[str], columns: List[str]
self, well: str, rows: list[str], columns: list[str]
) -> dict: # pragma: no cover
raise NotImplementedError()

@abstractmethod
def validate_well_dict(
self, well: dict, rows: List[str], columns: List[str]
self, well: dict, rows: list[str], columns: list[str]
) -> None: # pragma: no cover
raise NotImplementedError()

@abstractmethod
def generate_coordinate_transformations(
self, shapes: List[tuple]
) -> Optional[List[List[Dict[str, Any]]]]: # pragma: no cover
self, shapes: list[tuple]
) -> Optional[list[list[dict[str, Any]]]]: # pragma: no cover
raise NotImplementedError()

@abstractmethod
def validate_coordinate_transformations(
self,
ndim: int,
nlevels: int,
coordinate_transformations: Optional[List[List[Dict[str, Any]]]] = None,
) -> Optional[List[List[Dict[str, Any]]]]: # pragma: no cover
coordinate_transformations: Optional[list[list[dict[str, Any]]]] = None,
) -> Optional[list[list[dict[str, Any]]]]: # pragma: no cover
raise NotImplementedError()


Expand All @@ -122,7 +123,7 @@ class FormatV01(Format):
Initial format. (2020)
"""

REQUIRED_PLATE_WELL_KEYS: Dict[str, type] = {"path": str}
REQUIRED_PLATE_WELL_KEYS: dict[str, type] = {"path": str}

@property
def version(self) -> str:
Expand All @@ -139,12 +140,12 @@ def init_store(self, path: str, mode: str = "r") -> FSStore:
return store

def generate_well_dict(
self, well: str, rows: List[str], columns: List[str]
self, well: str, rows: list[str], columns: list[str]
) -> dict:
return {"path": str(well)}

def validate_well_dict(
self, well: dict, rows: List[str], columns: List[str]
self, well: dict, rows: list[str], columns: list[str]
) -> None:
if any(e not in self.REQUIRED_PLATE_WELL_KEYS for e in well.keys()):
LOGGER.debug("%s contains unspecified keys", well)
Expand All @@ -157,15 +158,15 @@ def validate_well_dict(
raise ValueError("%s path must be of %s type", well, key_type)

def generate_coordinate_transformations(
self, shapes: List[tuple]
) -> Optional[List[List[Dict[str, Any]]]]:
self, shapes: list[tuple]
) -> Optional[list[list[dict[str, Any]]]]:
return None

def validate_coordinate_transformations(
self,
ndim: int,
nlevels: int,
coordinate_transformations: Optional[List[List[Dict[str, Any]]]] = None,
coordinate_transformations: Optional[list[list[dict[str, Any]]]] = None,
) -> None:
return None

Expand Down Expand Up @@ -230,7 +231,7 @@ def version(self) -> str:
return "0.4"

def generate_well_dict(
self, well: str, rows: List[str], columns: List[str]
self, well: str, rows: list[str], columns: list[str]
) -> dict:
row, column = well.split("/")
if row not in rows:
Expand All @@ -242,7 +243,7 @@ def generate_well_dict(
return {"path": str(well), "rowIndex": rowIndex, "columnIndex": columnIndex}

def validate_well_dict(
self, well: dict, rows: List[str], columns: List[str]
self, well: dict, rows: list[str], columns: list[str]
) -> None:
super().validate_well_dict(well, rows, columns)
if len(well["path"].split("/")) != 2:
Expand All @@ -258,10 +259,10 @@ def validate_well_dict(
raise ValueError("Mismatching column index for %s", well)

def generate_coordinate_transformations(
self, shapes: List[tuple]
) -> Optional[List[List[Dict[str, Any]]]]:
self, shapes: list[tuple]
) -> Optional[list[list[dict[str, Any]]]]:
data_shape = shapes[0]
coordinate_transformations: List[List[Dict[str, Any]]] = []
coordinate_transformations: list[list[dict[str, Any]]] = []
# calculate minimal 'scale' transform based on pyramid dims
for shape in shapes:
assert len(shape) == len(data_shape)
Expand All @@ -274,7 +275,7 @@ def validate_coordinate_transformations(
self,
ndim: int,
nlevels: int,
coordinate_transformations: Optional[List[List[Dict[str, Any]]]] = None,
coordinate_transformations: Optional[list[list[dict[str, Any]]]] = None,
) -> None:
"""
Validates that a list of dicts contains a 'scale' transformation
Expand Down
4 changes: 2 additions & 2 deletions ome_zarr/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import json
import logging
from pathlib import Path
from typing import List, Optional, Union
from typing import Optional, Union
from urllib.parse import urljoin

import dask.array as da
Expand Down Expand Up @@ -165,7 +165,7 @@ def get_json(self, subpath: str) -> JSONDict:
LOGGER.exception("Error while loading JSON")
return {}

def parts(self) -> List[str]:
def parts(self) -> list[str]:
if self._isfile():
return list(Path(self.__path).parts)
else:
Expand Down
Loading
Loading