Skip to content

Commit 22fa187

Browse files
authored
Merge pull request #2031 from sydduckworth/type-checking-fixes
Added type hints to `_asdf.py` and `config.py`
2 parents a71bd10 + 8911045 commit 22fa187

26 files changed

Lines changed: 467 additions & 251 deletions

asdf/_asdf.py

Lines changed: 164 additions & 124 deletions
Large diffs are not rendered by default.

asdf/_commands/defragment.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,4 +74,5 @@ def defragment(input_, output=None, resolve_references=False, compress=None):
7474
ff2 = AsdfFile(ff)
7575
if resolve_references:
7676
ff2.resolve_references()
77-
ff2.write_to(output, all_array_storage="internal", all_array_compression=compress)
77+
if output is not None:
78+
ff2.write_to(output, all_array_storage="internal", all_array_compression=compress)

asdf/_compression.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from .exceptions import AsdfWarning
1010

1111

12-
def validate(compression):
12+
def validate(compression: str | bytes | None) -> str | None:
1313
"""
1414
Validate the compression string.
1515
@@ -318,7 +318,7 @@ def compress(fd, data, compression, config=None):
318318
# get a 1D array that preserves byteorder
319319
# Note: in Python < 3.12 numpy typing doesn't correctly reflect that arrays support buffer protocol
320320
# See also: https://github.com/numpy/numpy/issues/26783
321-
data = memoryview(np.frombuffer(data, dtype=data.format)) # type: ignore
321+
data = memoryview(np.frombuffer(data, dtype=data.format)) # pyrefly: ignore[bad-argument-type]
322322
if not data.contiguous:
323323
# the data will be contiguous by construction, but better safe than sorry!
324324
raise ValueError(data.contiguous)

asdf/_dump.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from io import BytesIO
22

33
from asdf._asdf import AsdfFile, open_asdf
4-
from asdf.util import NotSet
4+
from asdf.util import NOT_SET
55

66
__all__ = ["dump", "dumps", "load", "loads"]
77

@@ -12,9 +12,9 @@ def dump(
1212
*,
1313
version=None,
1414
extensions=None,
15-
all_array_storage=NotSet,
16-
all_array_compression=NotSet,
17-
compression_kwargs=NotSet,
15+
all_array_storage=NOT_SET,
16+
all_array_compression=NOT_SET,
17+
compression_kwargs=NOT_SET,
1818
pad_blocks=False,
1919
custom_schema=None,
2020
write_checksums=True,
@@ -75,9 +75,9 @@ def dumps(
7575
*,
7676
version=None,
7777
extensions=None,
78-
all_array_storage=NotSet,
79-
all_array_compression=NotSet,
80-
compression_kwargs=NotSet,
78+
all_array_storage=NOT_SET,
79+
all_array_compression=NOT_SET,
80+
compression_kwargs=NOT_SET,
8181
pad_blocks=False,
8282
custom_schema=None,
8383
write_checksums=True,

asdf/_io.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,14 @@
22
Low-level input/output routines for AsdfFile instances
33
"""
44

5+
from __future__ import annotations
6+
57
import contextlib
68
import io
79
import pathlib
10+
from typing import TypeVar
11+
12+
from asdf.versioning import AsdfVersion
813

914
from . import _version, constants, generic_io, versioning, yamlutil
1015
from ._block.manager import Manager as BlockManager
@@ -27,7 +32,7 @@ def get_asdf_library_info():
2732
)
2833

2934

30-
def parse_header_line(line):
35+
def parse_header_line(line: str) -> AsdfVersion:
3136
"""
3237
Parses the header line in a ASDF file to obtain the ASDF version.
3338
"""
@@ -84,7 +89,11 @@ def read_comment_section(fd):
8489
return comments
8590

8691

87-
def find_asdf_version_in_comments(comments, default=None):
92+
# Required for type narrowing in `find_asdf_version_in_comments``
93+
MaybeVer = TypeVar("MaybeVer", AsdfVersion, None)
94+
95+
96+
def find_asdf_version_in_comments(comments: list[str], default: MaybeVer = None) -> MaybeVer:
8897
for comment in comments:
8998
parts = comment.split()
9099
if len(parts) == 2 and parts[0] == constants.ASDF_STANDARD_COMMENT:

asdf/_jsonschema/_utils.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,10 @@
11
from collections.abc import Mapping, MutableMapping, Sequence
22
from urllib.parse import urlsplit
3+
from importlib import resources
4+
35
import itertools
46
import json
57
import re
6-
import sys
7-
8-
# The files() API was added in Python 3.9.
9-
if sys.version_info >= (3, 9): # pragma: no cover
10-
from importlib import resources
11-
else: # pragma: no cover
12-
import importlib_resources as resources # type: ignore
138

149

1510
class URIDict(MutableMapping):

asdf/_tests/test_array_blocks.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import io
44
import os
5+
from typing import Any
56

67
import numpy as np
78
import pytest
@@ -10,6 +11,7 @@
1011
from numpy.testing import assert_array_equal
1112

1213
import asdf
14+
import asdf.versioning
1315
from asdf import constants, generic_io
1416
from asdf._block import io as bio
1517
from asdf.exceptions import AsdfBlockIndexWarning
@@ -57,6 +59,8 @@ def test_invalid_array_storage():
5759
tree = {"my_array": my_array}
5860
ff = asdf.AsdfFile(tree)
5961
with pytest.raises(ValueError, match=r"array_storage must be one of.*"):
62+
# Intentionally incorrect storage type
63+
# pyrefly: ignore[bad-argument-type]
6064
ff.set_array_storage(my_array, "foo")
6165

6266

@@ -883,7 +887,9 @@ def test_add_block_before_fully_loaded(tmp_path):
883887
@pytest.mark.parametrize("all_array_storage", ["internal", "external", "inline"])
884888
@pytest.mark.parametrize("all_array_compression", [None, "", "zlib", "bzp2", "lz4", "input"])
885889
@pytest.mark.parametrize("compression_kwargs", [None, {}])
886-
def test_write_to_update_storage_options(tmp_path, all_array_storage, all_array_compression, compression_kwargs):
890+
def test_write_to_update_storage_options(
891+
tmp_path, all_array_storage, all_array_compression, compression_kwargs: dict[str, Any]
892+
):
887893
if all_array_compression == "bzp2" and compression_kwargs is not None:
888894
compression_kwargs = {"compresslevel": 1}
889895

asdf/_tests/test_asdf.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def url_mapping(self):
5252
return self._url_mapping
5353

5454
@property
55-
def extension_uri(self):
55+
def extension_uri(self) -> str | None:
5656
return self._extension_uri
5757

5858
@property
@@ -120,7 +120,8 @@ def test_asdf_file_extensions():
120120
msg = r"[The extensions parameter must be an extension.*, Extension must implement the Extension interface]"
121121
for arg in (object(), [object()]):
122122
with pytest.raises(TypeError, match=msg):
123-
AsdfFile(extensions=arg)
123+
# Ignore typing here because type is intentionally wrong
124+
AsdfFile(extensions=arg) # pyrefly: ignore[bad-argument-type]
124125

125126

126127
def test_asdf_file_version_requirement():
@@ -174,6 +175,8 @@ def test_open_asdf_extensions(tmp_path):
174175

175176
msg = r"[The extensions parameter must be an extension.*, Extension must implement the Extension interface]"
176177
for arg in (object(), [object()]):
178+
# Intentionally incorrect extension type
179+
# pyrefly: ignore[bad-argument-type]
177180
with pytest.raises(TypeError, match=msg), open_asdf(path, extensions=arg) as af:
178181
pass
179182

asdf/_tests/test_compression.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import io
22
import lzma
33
import os
4+
from typing import Any
45

56
import numpy as np
67
import pytest
@@ -26,7 +27,13 @@ def _get_sparse_tree():
2627
return {"science_data": arr}
2728

2829

29-
def _roundtrip(tmp_path, tree, compression=None, write_options=None, read_options=None):
30+
def _roundtrip(
31+
tmp_path,
32+
tree,
33+
compression=None,
34+
write_options: dict[str, Any] | None = None,
35+
read_options: dict[str, Any] | None = None,
36+
):
3037
read_options = {} if read_options is None else read_options
3138
write_options = {} if write_options is None else write_options.copy()
3239
write_options.update(all_array_compression=compression)
@@ -69,6 +76,8 @@ def test_invalid_compression():
6976
tree = _get_large_tree()
7077
ff = asdf.AsdfFile(tree)
7178
with pytest.raises(ValueError, match=r"Invalid compression type: foo"):
79+
# Intentionally incorrect compression type
80+
# pyrefly: ignore[bad-argument-type]
7281
ff.set_array_compression(tree["science_data"], "foo")
7382
with pytest.raises(ValueError, match=r"Unknown compression type: .*"):
7483
_compression._get_compressor("foo")

asdf/_tests/test_config.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,8 @@ def test_all_array_storage():
117117
config.all_array_storage = None
118118
assert get_config().all_array_storage is None
119119
with pytest.raises(ValueError, match=r"Invalid value for all_array_storage"):
120+
# Intentionally incorrect argument type
121+
# pyrefly: ignore[bad-argument-type]
120122
config.all_array_storage = "foo"
121123

122124

@@ -139,6 +141,8 @@ def test_all_array_compression_kwargs():
139141
config.all_array_compression_kwargs = None
140142
assert get_config().all_array_compression_kwargs is None
141143
with pytest.raises(ValueError, match=r"Invalid value for all_array_compression_kwargs"):
144+
# Intentionally incorrect argument type
145+
# pyrefly: ignore[bad-argument-type]
142146
config.all_array_compression_kwargs = "foo"
143147

144148

0 commit comments

Comments
 (0)