Skip to content

Commit

Permalink
Convert Optional[] to union types (#252)
Browse files Browse the repository at this point in the history
  • Loading branch information
mojaveazure authored Dec 19, 2024
1 parent 6fc087f commit faab36a
Show file tree
Hide file tree
Showing 12 changed files with 150 additions and 133 deletions.
10 changes: 6 additions & 4 deletions python-spec/src/somacore/_mixin.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""Tools for making mixins with SOMA Collections."""

from typing import Generic, MutableMapping, Optional, Type, TypeVar, Union, overload
from __future__ import annotations

from typing import Generic, MutableMapping, Type, TypeVar, Union, overload

import attrs

Expand Down Expand Up @@ -35,10 +37,10 @@ class FSCollection(FirstSecondMixin, CollectionBase):
inst.second = 500
"""

typ: Optional[Type[_T]] = None
typ: Type[_T] | None = None
"""The type we expect to return from this field."""

item_name: Optional[str] = None
item_name: str | None = None
"""The name of the item we are getting (``x._backing["whatever"]``).
This uses the name of the field by default but can be manually overridden.
Expand All @@ -59,7 +61,7 @@ def __get__(self, inst: None, owner: Type[_Coll]) -> "item[_T]": ...
@overload
def __get__(self, inst: _Coll, owner: Type[_Coll]) -> _T: ...

def __get__(self, inst: Optional[_Coll], owner: Type[_Coll]) -> Union["item", _T]:
def __get__(self, inst: _Coll | None, owner: Type[_Coll]) -> Union["item", _T]:
del owner # unused
if not inst:
return self
Expand Down
12 changes: 7 additions & 5 deletions python-spec/src/somacore/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
members will be exported to the ``somacore`` namespace.
"""

from __future__ import annotations

import abc
from typing import Any, ClassVar, MutableMapping, Optional
from typing import Any, ClassVar, MutableMapping

from typing_extensions import LiteralString, Self

Expand All @@ -25,8 +27,8 @@ def open(
uri: str,
mode: options.OpenMode = "r",
*,
context: Optional[Any] = None,
platform_config: Optional[options.PlatformConfig] = None,
context: Any | None = None,
platform_config: options.PlatformConfig | None = None,
) -> Self:
"""Opens the SOMA object of this type at the given URI.
Expand All @@ -43,7 +45,7 @@ def open(

@classmethod
@abc.abstractmethod
def exists(cls, uri: str, *, context: Optional[Any] = None) -> bool:
def exists(cls, uri: str, *, context: Any | None = None) -> bool:
"""Checks whether a SOMA object of this type is stored at the URI.
Args:
Expand All @@ -66,7 +68,7 @@ def uri(self) -> str:
raise NotImplementedError()

@property
def context(self) -> Optional[types.ContextBase]:
def context(self) -> types.ContextBase | None:
"""A value storing implementation-specific configuration information.
This contains long-lived (i.e., not call-specific) information that is
Expand Down
37 changes: 19 additions & 18 deletions python-spec/src/somacore/collection.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from __future__ import annotations

import abc
from typing import (
Any,
MutableMapping,
Optional,
Sequence,
Tuple,
Type,
Expand Down Expand Up @@ -43,8 +44,8 @@ def create(
cls,
uri: str,
*,
platform_config: Optional[options.PlatformConfig] = None,
context: Optional[Any] = None,
platform_config: options.PlatformConfig | None = None,
context: Any | None = None,
) -> Self:
"""Creates a new collection of this type at the given URI.
Expand All @@ -69,8 +70,8 @@ def add_new_collection(
key: str,
kind: None = None,
*,
uri: Optional[str] = ...,
platform_config: Optional[options.PlatformConfig] = ...,
uri: str | None = ...,
platform_config: options.PlatformConfig | None = ...,
) -> "Collection": ...

@overload
Expand All @@ -80,18 +81,18 @@ def add_new_collection(
key: str,
kind: Type[_CT],
*,
uri: Optional[str] = ...,
platform_config: Optional[options.PlatformConfig] = ...,
uri: str | None = ...,
platform_config: options.PlatformConfig | None = ...,
) -> _CT: ...

@abc.abstractmethod
def add_new_collection(
self,
key: str,
kind: Optional[Type["BaseCollection"]] = None,
kind: Type["BaseCollection"] | None = None,
*,
uri: Optional[str] = None,
platform_config: Optional[options.PlatformConfig] = None,
uri: str | None = None,
platform_config: options.PlatformConfig | None = None,
) -> "BaseCollection":
"""Creates a new sub-collection of this collection.
To add an existing collection as a sub-element of this collection,
Expand Down Expand Up @@ -151,11 +152,11 @@ def add_new_dataframe(
self,
key: str,
*,
uri: Optional[str] = None,
uri: str | None = None,
schema: pa.Schema,
index_column_names: Sequence[str] = (options.SOMA_JOINID,),
domain: Optional[Sequence[Optional[Tuple[Any, Any]]]] = None,
platform_config: Optional[options.PlatformConfig] = None,
domain: Sequence[Tuple[Any, Any] | None] | None = None,
platform_config: options.PlatformConfig | None = None,
) -> data.DataFrame:
"""Creates a new DataFrame as a child of this collection.
Expand All @@ -174,10 +175,10 @@ def add_new_dense_ndarray(
self,
key: str,
*,
uri: Optional[str] = None,
uri: str | None = None,
type: pa.DataType,
shape: Sequence[int],
platform_config: Optional[options.PlatformConfig] = None,
platform_config: options.PlatformConfig | None = None,
) -> data.DenseNDArray:
"""Creates a new dense NDArray as a child of this collection.
Expand All @@ -196,10 +197,10 @@ def add_new_sparse_ndarray(
self,
key: str,
*,
uri: Optional[str] = None,
uri: str | None = None,
type: pa.DataType,
shape: Sequence[int],
platform_config: Optional[options.PlatformConfig] = None,
platform_config: options.PlatformConfig | None = None,
) -> data.SparseNDArray:
"""Creates a new sparse NDArray as a child of this collection.
Expand All @@ -219,7 +220,7 @@ def __setitem__(self, key: str, value: _Elem) -> None:

@abc.abstractmethod
def set(
self, key: str, value: _Elem, *, use_relative_uri: Optional[bool] = None
self, key: str, value: _Elem, *, use_relative_uri: bool | None = None
) -> Self:
"""Sets an entry of this collection.
Expand Down
6 changes: 4 additions & 2 deletions python-spec/src/somacore/coordinates.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
"""Definitions of types related to coordinate systems."""

from __future__ import annotations

import abc
import collections.abc
import itertools
from typing import Iterable, Optional, Sequence, Tuple, Union
from typing import Iterable, Sequence, Tuple, Union

import attrs
import numpy as np
Expand All @@ -23,7 +25,7 @@ class Axis:

name: str
"""Name of the axis."""
unit: Optional[str] = None
unit: str | None = None
"""Optional string name for the units of the axis."""


Expand Down
37 changes: 19 additions & 18 deletions python-spec/src/somacore/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@
Default values are provided here as a reference for implementors.
"""

from __future__ import annotations

import abc
from typing import (
Any,
ClassVar,
Iterator,
List,
Optional,
Sequence,
Tuple,
TypeVar,
Expand Down Expand Up @@ -51,9 +52,9 @@ def create(
*,
schema: pa.Schema,
index_column_names: Sequence[str] = (options.SOMA_JOINID,),
domain: Optional[Sequence[Optional[Tuple[Any, Any]]]] = None,
platform_config: Optional[options.PlatformConfig] = None,
context: Optional[Any] = None,
domain: Sequence[Tuple[Any, Any] | None] | None = None,
platform_config: options.PlatformConfig | None = None,
context: Any | None = None,
) -> Self:
"""Creates a new ``DataFrame`` at the given URI.
Expand Down Expand Up @@ -112,13 +113,13 @@ def create(
def read(
self,
coords: options.SparseDFCoords = (),
column_names: Optional[Sequence[str]] = None,
column_names: Sequence[str] | None = None,
*,
batch_size: options.BatchSize = options.BatchSize(),
partitions: Optional[options.ReadPartitions] = None,
partitions: options.ReadPartitions | None = None,
result_order: options.ResultOrderStr = _RO_AUTO,
value_filter: Optional[str] = None,
platform_config: Optional[options.PlatformConfig] = None,
value_filter: str | None = None,
platform_config: options.PlatformConfig | None = None,
) -> "ReadIter[pa.Table]":
"""Reads a user-defined slice of data into Arrow tables.
Expand Down Expand Up @@ -218,7 +219,7 @@ def write(
self,
values: Union[pa.RecordBatch, pa.Table],
*,
platform_config: Optional[options.PlatformConfig] = None,
platform_config: options.PlatformConfig | None = None,
) -> Self:
"""Writes the data from an Arrow table to the persistent object.
Expand Down Expand Up @@ -283,9 +284,9 @@ def create(
uri: str,
*,
type: pa.DataType,
shape: Sequence[Optional[int]],
platform_config: Optional[options.PlatformConfig] = None,
context: Optional[Any] = None,
shape: Sequence[int | None],
platform_config: options.PlatformConfig | None = None,
context: Any | None = None,
) -> Self:
"""Creates a new ND array of the current type at the given URI.
Expand Down Expand Up @@ -376,9 +377,9 @@ def read(
self,
coords: options.DenseNDCoords = (),
*,
partitions: Optional[options.ReadPartitions] = None,
partitions: options.ReadPartitions | None = None,
result_order: options.ResultOrderStr = _RO_AUTO,
platform_config: Optional[options.PlatformConfig] = None,
platform_config: options.PlatformConfig | None = None,
) -> pa.Tensor:
"""Reads the specified subarray as a Tensor.
Expand Down Expand Up @@ -432,7 +433,7 @@ def write(
coords: options.DenseNDCoords,
values: pa.Tensor,
*,
platform_config: Optional[options.PlatformConfig] = None,
platform_config: options.PlatformConfig | None = None,
) -> Self:
"""Writes an Arrow tensor to a subarray of the persistent object.
Expand Down Expand Up @@ -476,9 +477,9 @@ def read(
coords: options.SparseNDCoords = (),
*,
batch_size: options.BatchSize = options.BatchSize(),
partitions: Optional[options.ReadPartitions] = None,
partitions: options.ReadPartitions | None = None,
result_order: options.ResultOrderStr = _RO_AUTO,
platform_config: Optional[options.PlatformConfig] = None,
platform_config: options.PlatformConfig | None = None,
) -> "SparseRead":
"""Reads the specified subarray in batches.
Expand Down Expand Up @@ -537,7 +538,7 @@ def write(
self,
values: SparseArrowData,
*,
platform_config: Optional[options.PlatformConfig] = None,
platform_config: options.PlatformConfig | None = None,
) -> Self:
"""Writes a Tensor to a subarray of the persistent object.
Expand Down
8 changes: 5 additions & 3 deletions python-spec/src/somacore/experiment.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from __future__ import annotations

from abc import ABC
from abc import abstractmethod
from typing import Generic, Optional, TypeVar
from typing import Generic, TypeVar

from typing_extensions import Final

Expand Down Expand Up @@ -71,8 +73,8 @@ def axis_query(
self,
measurement_name: str,
*,
obs_query: Optional[query.AxisQuery] = None,
var_query: Optional[query.AxisQuery] = None,
var_query: query.AxisQuery | None = None,
obs_query: query.AxisQuery | None = None,
) -> ExperimentAxisQuery:
"""Creates an axis query over this experiment.
Expand Down
8 changes: 5 additions & 3 deletions python-spec/src/somacore/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
SOMA types that require them, not reimplemented by the implementing package.
"""

from __future__ import annotations

import enum
from typing import Any, Dict, Mapping, Optional, Sequence, TypeVar, Union
from typing import Any, Dict, Mapping, Sequence, TypeVar, Union

import attrs
import numpy as np
Expand Down Expand Up @@ -89,9 +91,9 @@ class BatchSize:
Experimental
"""

count: Optional[int] = attrs.field(default=None)
count: int | None = attrs.field(default=None)
"""``arrow.Table``s with this number of rows will be returned."""
bytes: Optional[int] = attrs.field(default=None)
bytes: int | None = attrs.field(default=None)
"""Data of up to this size in bytes will be returned."""

@count.validator
Expand Down
6 changes: 4 additions & 2 deletions python-spec/src/somacore/query/axis.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from typing import Optional, Sequence, Tuple
from __future__ import annotations

from typing import Sequence, Tuple

import attrs
import numpy as np
Expand Down Expand Up @@ -81,7 +83,7 @@ class AxisQuery:
Lifecycle: maturing
"""

value_filter: Optional[str] = attrs.field(
value_filter: str | None = attrs.field(
default=None,
validator=attrs.validators.optional(attrs.validators.instance_of(str)),
)
Expand Down
Loading

0 comments on commit faab36a

Please sign in to comment.