Skip to content

Commit faab36a

Browse files
authored
Convert Optional[] to union types (#252)
Convert `Optional[]` to [union types](https://docs.python.org/3/library/stdtypes.html#union-type) in type hints [SC-61053](https://app.shortcut.com/tiledb-inc/story/61053) resolves single-cell-data/TileDB-SOMA#3334
1 parent 6fc087f commit faab36a

12 files changed

Lines changed: 150 additions & 133 deletions

File tree

python-spec/src/somacore/_mixin.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
"""Tools for making mixins with SOMA Collections."""
22

3-
from typing import Generic, MutableMapping, Optional, Type, TypeVar, Union, overload
3+
from __future__ import annotations
4+
5+
from typing import Generic, MutableMapping, Type, TypeVar, Union, overload
46

57
import attrs
68

@@ -35,10 +37,10 @@ class FSCollection(FirstSecondMixin, CollectionBase):
3537
inst.second = 500
3638
"""
3739

38-
typ: Optional[Type[_T]] = None
40+
typ: Type[_T] | None = None
3941
"""The type we expect to return from this field."""
4042

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

62-
def __get__(self, inst: Optional[_Coll], owner: Type[_Coll]) -> Union["item", _T]:
64+
def __get__(self, inst: _Coll | None, owner: Type[_Coll]) -> Union["item", _T]:
6365
del owner # unused
6466
if not inst:
6567
return self

python-spec/src/somacore/base.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@
44
members will be exported to the ``somacore`` namespace.
55
"""
66

7+
from __future__ import annotations
8+
79
import abc
8-
from typing import Any, ClassVar, MutableMapping, Optional
10+
from typing import Any, ClassVar, MutableMapping
911

1012
from typing_extensions import LiteralString, Self
1113

@@ -25,8 +27,8 @@ def open(
2527
uri: str,
2628
mode: options.OpenMode = "r",
2729
*,
28-
context: Optional[Any] = None,
29-
platform_config: Optional[options.PlatformConfig] = None,
30+
context: Any | None = None,
31+
platform_config: options.PlatformConfig | None = None,
3032
) -> Self:
3133
"""Opens the SOMA object of this type at the given URI.
3234
@@ -43,7 +45,7 @@ def open(
4345

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

6870
@property
69-
def context(self) -> Optional[types.ContextBase]:
71+
def context(self) -> types.ContextBase | None:
7072
"""A value storing implementation-specific configuration information.
7173
7274
This contains long-lived (i.e., not call-specific) information that is

python-spec/src/somacore/collection.py

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1+
from __future__ import annotations
2+
13
import abc
24
from typing import (
35
Any,
46
MutableMapping,
5-
Optional,
67
Sequence,
78
Tuple,
89
Type,
@@ -43,8 +44,8 @@ def create(
4344
cls,
4445
uri: str,
4546
*,
46-
platform_config: Optional[options.PlatformConfig] = None,
47-
context: Optional[Any] = None,
47+
platform_config: options.PlatformConfig | None = None,
48+
context: Any | None = None,
4849
) -> Self:
4950
"""Creates a new collection of this type at the given URI.
5051
@@ -69,8 +70,8 @@ def add_new_collection(
6970
key: str,
7071
kind: None = None,
7172
*,
72-
uri: Optional[str] = ...,
73-
platform_config: Optional[options.PlatformConfig] = ...,
73+
uri: str | None = ...,
74+
platform_config: options.PlatformConfig | None = ...,
7475
) -> "Collection": ...
7576

7677
@overload
@@ -80,18 +81,18 @@ def add_new_collection(
8081
key: str,
8182
kind: Type[_CT],
8283
*,
83-
uri: Optional[str] = ...,
84-
platform_config: Optional[options.PlatformConfig] = ...,
84+
uri: str | None = ...,
85+
platform_config: options.PlatformConfig | None = ...,
8586
) -> _CT: ...
8687

8788
@abc.abstractmethod
8889
def add_new_collection(
8990
self,
9091
key: str,
91-
kind: Optional[Type["BaseCollection"]] = None,
92+
kind: Type["BaseCollection"] | None = None,
9293
*,
93-
uri: Optional[str] = None,
94-
platform_config: Optional[options.PlatformConfig] = None,
94+
uri: str | None = None,
95+
platform_config: options.PlatformConfig | None = None,
9596
) -> "BaseCollection":
9697
"""Creates a new sub-collection of this collection.
9798
To add an existing collection as a sub-element of this collection,
@@ -151,11 +152,11 @@ def add_new_dataframe(
151152
self,
152153
key: str,
153154
*,
154-
uri: Optional[str] = None,
155+
uri: str | None = None,
155156
schema: pa.Schema,
156157
index_column_names: Sequence[str] = (options.SOMA_JOINID,),
157-
domain: Optional[Sequence[Optional[Tuple[Any, Any]]]] = None,
158-
platform_config: Optional[options.PlatformConfig] = None,
158+
domain: Sequence[Tuple[Any, Any] | None] | None = None,
159+
platform_config: options.PlatformConfig | None = None,
159160
) -> data.DataFrame:
160161
"""Creates a new DataFrame as a child of this collection.
161162
@@ -174,10 +175,10 @@ def add_new_dense_ndarray(
174175
self,
175176
key: str,
176177
*,
177-
uri: Optional[str] = None,
178+
uri: str | None = None,
178179
type: pa.DataType,
179180
shape: Sequence[int],
180-
platform_config: Optional[options.PlatformConfig] = None,
181+
platform_config: options.PlatformConfig | None = None,
181182
) -> data.DenseNDArray:
182183
"""Creates a new dense NDArray as a child of this collection.
183184
@@ -196,10 +197,10 @@ def add_new_sparse_ndarray(
196197
self,
197198
key: str,
198199
*,
199-
uri: Optional[str] = None,
200+
uri: str | None = None,
200201
type: pa.DataType,
201202
shape: Sequence[int],
202-
platform_config: Optional[options.PlatformConfig] = None,
203+
platform_config: options.PlatformConfig | None = None,
203204
) -> data.SparseNDArray:
204205
"""Creates a new sparse NDArray as a child of this collection.
205206
@@ -219,7 +220,7 @@ def __setitem__(self, key: str, value: _Elem) -> None:
219220

220221
@abc.abstractmethod
221222
def set(
222-
self, key: str, value: _Elem, *, use_relative_uri: Optional[bool] = None
223+
self, key: str, value: _Elem, *, use_relative_uri: bool | None = None
223224
) -> Self:
224225
"""Sets an entry of this collection.
225226

python-spec/src/somacore/coordinates.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
"""Definitions of types related to coordinate systems."""
22

3+
from __future__ import annotations
4+
35
import abc
46
import collections.abc
57
import itertools
6-
from typing import Iterable, Optional, Sequence, Tuple, Union
8+
from typing import Iterable, Sequence, Tuple, Union
79

810
import attrs
911
import numpy as np
@@ -23,7 +25,7 @@ class Axis:
2325

2426
name: str
2527
"""Name of the axis."""
26-
unit: Optional[str] = None
28+
unit: str | None = None
2729
"""Optional string name for the units of the axis."""
2830

2931

python-spec/src/somacore/data.py

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,14 @@
66
Default values are provided here as a reference for implementors.
77
"""
88

9+
from __future__ import annotations
10+
911
import abc
1012
from typing import (
1113
Any,
1214
ClassVar,
1315
Iterator,
1416
List,
15-
Optional,
1617
Sequence,
1718
Tuple,
1819
TypeVar,
@@ -51,9 +52,9 @@ def create(
5152
*,
5253
schema: pa.Schema,
5354
index_column_names: Sequence[str] = (options.SOMA_JOINID,),
54-
domain: Optional[Sequence[Optional[Tuple[Any, Any]]]] = None,
55-
platform_config: Optional[options.PlatformConfig] = None,
56-
context: Optional[Any] = None,
55+
domain: Sequence[Tuple[Any, Any] | None] | None = None,
56+
platform_config: options.PlatformConfig | None = None,
57+
context: Any | None = None,
5758
) -> Self:
5859
"""Creates a new ``DataFrame`` at the given URI.
5960
@@ -112,13 +113,13 @@ def create(
112113
def read(
113114
self,
114115
coords: options.SparseDFCoords = (),
115-
column_names: Optional[Sequence[str]] = None,
116+
column_names: Sequence[str] | None = None,
116117
*,
117118
batch_size: options.BatchSize = options.BatchSize(),
118-
partitions: Optional[options.ReadPartitions] = None,
119+
partitions: options.ReadPartitions | None = None,
119120
result_order: options.ResultOrderStr = _RO_AUTO,
120-
value_filter: Optional[str] = None,
121-
platform_config: Optional[options.PlatformConfig] = None,
121+
value_filter: str | None = None,
122+
platform_config: options.PlatformConfig | None = None,
122123
) -> "ReadIter[pa.Table]":
123124
"""Reads a user-defined slice of data into Arrow tables.
124125
@@ -218,7 +219,7 @@ def write(
218219
self,
219220
values: Union[pa.RecordBatch, pa.Table],
220221
*,
221-
platform_config: Optional[options.PlatformConfig] = None,
222+
platform_config: options.PlatformConfig | None = None,
222223
) -> Self:
223224
"""Writes the data from an Arrow table to the persistent object.
224225
@@ -283,9 +284,9 @@ def create(
283284
uri: str,
284285
*,
285286
type: pa.DataType,
286-
shape: Sequence[Optional[int]],
287-
platform_config: Optional[options.PlatformConfig] = None,
288-
context: Optional[Any] = None,
287+
shape: Sequence[int | None],
288+
platform_config: options.PlatformConfig | None = None,
289+
context: Any | None = None,
289290
) -> Self:
290291
"""Creates a new ND array of the current type at the given URI.
291292
@@ -376,9 +377,9 @@ def read(
376377
self,
377378
coords: options.DenseNDCoords = (),
378379
*,
379-
partitions: Optional[options.ReadPartitions] = None,
380+
partitions: options.ReadPartitions | None = None,
380381
result_order: options.ResultOrderStr = _RO_AUTO,
381-
platform_config: Optional[options.PlatformConfig] = None,
382+
platform_config: options.PlatformConfig | None = None,
382383
) -> pa.Tensor:
383384
"""Reads the specified subarray as a Tensor.
384385
@@ -432,7 +433,7 @@ def write(
432433
coords: options.DenseNDCoords,
433434
values: pa.Tensor,
434435
*,
435-
platform_config: Optional[options.PlatformConfig] = None,
436+
platform_config: options.PlatformConfig | None = None,
436437
) -> Self:
437438
"""Writes an Arrow tensor to a subarray of the persistent object.
438439
@@ -476,9 +477,9 @@ def read(
476477
coords: options.SparseNDCoords = (),
477478
*,
478479
batch_size: options.BatchSize = options.BatchSize(),
479-
partitions: Optional[options.ReadPartitions] = None,
480+
partitions: options.ReadPartitions | None = None,
480481
result_order: options.ResultOrderStr = _RO_AUTO,
481-
platform_config: Optional[options.PlatformConfig] = None,
482+
platform_config: options.PlatformConfig | None = None,
482483
) -> "SparseRead":
483484
"""Reads the specified subarray in batches.
484485
@@ -537,7 +538,7 @@ def write(
537538
self,
538539
values: SparseArrowData,
539540
*,
540-
platform_config: Optional[options.PlatformConfig] = None,
541+
platform_config: options.PlatformConfig | None = None,
541542
) -> Self:
542543
"""Writes a Tensor to a subarray of the persistent object.
543544

python-spec/src/somacore/experiment.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
from __future__ import annotations
2+
13
from abc import ABC
24
from abc import abstractmethod
3-
from typing import Generic, Optional, TypeVar
5+
from typing import Generic, TypeVar
46

57
from typing_extensions import Final
68

@@ -71,8 +73,8 @@ def axis_query(
7173
self,
7274
measurement_name: str,
7375
*,
74-
obs_query: Optional[query.AxisQuery] = None,
75-
var_query: Optional[query.AxisQuery] = None,
76+
var_query: query.AxisQuery | None = None,
77+
obs_query: query.AxisQuery | None = None,
7678
) -> ExperimentAxisQuery:
7779
"""Creates an axis query over this experiment.
7880

python-spec/src/somacore/options.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@
44
SOMA types that require them, not reimplemented by the implementing package.
55
"""
66

7+
from __future__ import annotations
8+
79
import enum
8-
from typing import Any, Dict, Mapping, Optional, Sequence, TypeVar, Union
10+
from typing import Any, Dict, Mapping, Sequence, TypeVar, Union
911

1012
import attrs
1113
import numpy as np
@@ -89,9 +91,9 @@ class BatchSize:
8991
Experimental
9092
"""
9193

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

9799
@count.validator

python-spec/src/somacore/query/axis.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
from typing import Optional, Sequence, Tuple
1+
from __future__ import annotations
2+
3+
from typing import Sequence, Tuple
24

35
import attrs
46
import numpy as np
@@ -81,7 +83,7 @@ class AxisQuery:
8183
Lifecycle: maturing
8284
"""
8385

84-
value_filter: Optional[str] = attrs.field(
86+
value_filter: str | None = attrs.field(
8587
default=None,
8688
validator=attrs.validators.optional(attrs.validators.instance_of(str)),
8789
)

0 commit comments

Comments
 (0)