Skip to content

Commit 6841066

Browse files
author
Phil Varner
authored
fix typing in StacApiIO (#229)
* fix stac_api_io types * remove ignore-missing-imports
1 parent e4b3bd3 commit 6841066

File tree

5 files changed

+44
-43
lines changed

5 files changed

+44
-43
lines changed

.pre-commit-config.yaml

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -25,15 +25,13 @@ repos:
2525
hooks:
2626
- id: isort
2727
name: isort (python)
28-
# - repo: https://github.com/pre-commit/mirrors-mypy
29-
# rev: v0.960
30-
# hooks:
31-
# - id: mypy
32-
# files: ".*\\.py$"
33-
# exclude: ^(docs/.*|tests/.*)$
34-
# args:
35-
# - --ignore-missing-imports
36-
# additional_dependencies:
37-
# - pystac
38-
# - types-requests
39-
# - types-python-dateutil
28+
- repo: https://github.com/pre-commit/mirrors-mypy
29+
rev: v0.960
30+
hooks:
31+
- id: mypy
32+
files: ".*\\.py$"
33+
exclude: ^tests/.*$
34+
additional_dependencies:
35+
- pystac
36+
- types-requests
37+
- types-python-dateutil

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
88

99
### Added
1010

11+
- Significantly improved type hints
1112
- lru_cache to several methods [#167](https://github.com/stac-utils/pystac-client/pull/167)
1213
- Direct item GET via ogcapi-features, if conformant [#166](https://github.com/stac-utils/pystac-client/pull/166)
1314
- `py.typed` for downstream type checking [#163](https://github.com/stac-utils/pystac-client/pull/163)

docs/conf.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import subprocess
99
import sys
1010
from pathlib import Path
11+
from typing import List
1112

1213
# -- Path setup --------------------------------------------------------------
1314

@@ -16,7 +17,7 @@
1617
# documentation root, use os.path.abspath to make it absolute, like shown here.
1718
#
1819
sys.path.insert(0, str(Path(__file__).parent.parent.parent.resolve()))
19-
from pystac_client import __version__ # noqa: E402
20+
from pystac_client import __version__ # type: ignore # noqa: E402
2021

2122
git_branch = (
2223
subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"])
@@ -34,7 +35,7 @@
3435
package_description = "A Python client for the STAC and STAC-API specs"
3536

3637
# The full version, including alpha/beta/rc tags
37-
version = re.fullmatch(r"^(\d+\.\d+\.\d).*$", __version__).group(1)
38+
version = re.fullmatch(r"^(\d+\.\d+\.\d).*$", __version__).group(1) # type: ignore
3839
release = __version__
3940

4041

@@ -92,7 +93,7 @@
9293
# Add any paths that contain custom static files (such as style sheets) here,
9394
# relative to this directory. They are copied after the builtin static files,
9495
# so a file named "default.css" will overwrite the builtin "default.css".
95-
html_static_path = []
96+
html_static_path: List[str] = []
9697

9798
# -- Options for intersphinx extension ---------------------------------------
9899

pystac_client/client.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ def _supports_collections(self) -> bool:
110110
)
111111

112112
def _conforms_to(self, conformance_class: ConformanceClasses) -> bool:
113-
return self._stac_io.conforms_to(conformance_class)
113+
return self._stac_io.conforms_to(conformance_class) # type: ignore
114114

115115
@classmethod
116116
def from_dict(
@@ -122,7 +122,8 @@ def from_dict(
122122
preserve_dict: bool = True,
123123
) -> "Client":
124124
try:
125-
return super().from_dict(
125+
# this will return a Client because we have used a StacApiIO instance
126+
return super().from_dict( # type: ignore
126127
d=d, href=href, root=root, migrate=migrate, preserve_dict=preserve_dict
127128
)
128129
except pystac.STACTypeError:

pystac_client/stac_api_io.py

Lines changed: 26 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import logging
33
import re
44
from copy import deepcopy
5-
from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional, Union
5+
from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional
66
from urllib.parse import urlparse
77

88
import pystac
@@ -50,33 +50,19 @@ def __init__(
5050
# TODO - this should super() to parent class
5151
self.session = Session()
5252
self.session.headers.update(headers or {})
53-
self.session.params.update(parameters or {})
53+
self.session.params.update(parameters or {}) # type: ignore
5454

5555
self._conformance = conformance
5656

57-
def read_text(
58-
self,
59-
source: Union[str, Link],
60-
*args: Any,
61-
parameters: Optional[Dict[str, Any]] = None,
62-
**kwargs: Any,
63-
) -> str:
57+
def read_text(self, source: pystac.link.HREF, *args: Any, **kwargs: Any) -> str:
6458
"""Read text from the given URI.
6559
6660
Overwrites the default method for reading text from a URL or file to allow
6761
:class:`urllib.request.Request` instances as input. This method also raises
6862
any :exc:`urllib.error.HTTPError` exceptions rather than catching
6963
them to allow us to handle different response status codes as needed.
7064
"""
71-
if isinstance(source, str):
72-
href = source
73-
if bool(urlparse(href).scheme):
74-
return self.request(href, *args, parameters=parameters, **kwargs)
75-
else:
76-
with open(href) as f:
77-
href_contents = f.read()
78-
return href_contents
79-
elif isinstance(source, Link):
65+
if isinstance(source, Link):
8066
link = source.to_dict()
8167
href = link["href"]
8268
# get headers and body from Link and add to request from simple STAC
@@ -93,13 +79,26 @@ def read_text(
9379
# If "POST" use the body object that and respect the "merge" property.
9480
link_body = link.get("body", {})
9581
if method == "POST":
96-
parameters = {**parameters, **link_body} if merge else link_body
82+
parameters = (
83+
{**(kwargs.get("parameters", {})), **link_body}
84+
if merge
85+
else link_body
86+
)
9787
else:
9888
# parameters are already in the link href
9989
parameters = {}
90+
10091
return self.request(
101-
href, *args, method=method, headers=headers, parameters=parameters
92+
href, method=method, headers=headers, parameters=parameters
10293
)
94+
else: # str or something that can be str'ed
95+
href = str(source)
96+
if bool(urlparse(href).scheme):
97+
return self.request(href, *args, **kwargs)
98+
else:
99+
with open(href) as f:
100+
href_contents = f.read()
101+
return href_contents
103102

104103
def request(
105104
self,
@@ -157,7 +156,7 @@ def write_text_to_href(self, href: str, *args: Any, **kwargs: Any) -> None:
157156
def stac_object_from_dict(
158157
self,
159158
d: Dict[str, Any],
160-
href: Optional[str] = None,
159+
href: Optional[pystac.link.HREF] = None,
161160
root: Optional["Catalog_Type"] = None,
162161
preserve_dict: bool = True,
163162
) -> "STACObject_Type":
@@ -181,27 +180,27 @@ def stac_object_from_dict(
181180

182181
# Merge common properties in case this is an older STAC object.
183182
merge_common_properties(
184-
d, json_href=href, collection_cache=collection_cache
183+
d, json_href=str(href), collection_cache=collection_cache
185184
)
186185

187186
info = identify_stac_object(d)
188187
d = migrate_to_latest(d, info)
189188

190189
if info.object_type == pystac.STACObjectType.CATALOG:
191190
result = pystac_client.client.Client.from_dict(
192-
d, href=href, root=root, migrate=False, preserve_dict=preserve_dict
191+
d, href=str(href), root=root, migrate=False, preserve_dict=preserve_dict
193192
)
194193
result._stac_io = self
195194
return result
196195

197196
if info.object_type == pystac.STACObjectType.COLLECTION:
198197
return pystac_client.collection_client.CollectionClient.from_dict(
199-
d, href=href, root=root, migrate=False, preserve_dict=preserve_dict
198+
d, href=str(href), root=root, migrate=False, preserve_dict=preserve_dict
200199
)
201200

202201
if info.object_type == pystac.STACObjectType.ITEM:
203202
return pystac.Item.from_dict(
204-
d, href=href, root=root, migrate=False, preserve_dict=preserve_dict
203+
d, href=str(href), root=root, migrate=False, preserve_dict=preserve_dict
205204
)
206205

207206
raise ValueError(f"Unknown STAC object type {info.object_type}")
@@ -254,7 +253,8 @@ def conforms_to(self, conformance_class: ConformanceClasses) -> bool:
254253
provides such an endpoint.
255254
256255
Args:
257-
key : The ``ConformanceClasses`` key to check conformance against.
256+
conformance_class : The ``ConformanceClasses`` key to check conformance
257+
against.
258258
259259
Return:
260260
bool: Indicates if the API conforms to the given spec or URI.

0 commit comments

Comments
 (0)