Skip to content

Commit

Permalink
Issue #460 avoid string (return) annotations (large cases)
Browse files Browse the repository at this point in the history
PEP 563: Postponed Evaluation of Annotations
  • Loading branch information
soxofaan committed Aug 28, 2023
1 parent 72ce282 commit 346f5f3
Show file tree
Hide file tree
Showing 4 changed files with 152 additions and 155 deletions.
34 changes: 18 additions & 16 deletions openeo/metadata.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import logging
import warnings
from typing import Any, Callable, List, NamedTuple, Optional, Tuple, Union
Expand Down Expand Up @@ -32,11 +34,11 @@ def __repr__(self):
def __eq__(self, other):
return self.__class__ == other.__class__ and self.__dict__ == other.__dict__

def rename(self, name) -> 'Dimension':
def rename(self, name) -> Dimension:
"""Create new dimension with new name."""
return Dimension(type=self.type, name=name)

def rename_labels(self, target, source) -> 'Dimension':
def rename_labels(self, target, source) -> Dimension:
"""
Rename labels, if the type of dimension allows it.
Expand Down Expand Up @@ -67,7 +69,7 @@ def __init__(
self.crs = crs
self.step = step

def rename(self, name) -> 'Dimension':
def rename(self, name) -> Dimension:
return SpatialDimension(name=name, extent=self.extent, crs=self.crs, step=self.step)


Expand All @@ -76,7 +78,7 @@ def __init__(self, name: str, extent: Union[Tuple[str, str], List[str]]):
super().__init__(type="temporal", name=name)
self.extent = extent

def rename(self, name) -> 'Dimension':
def rename(self, name) -> Dimension:
return TemporalDimension(name=name, extent=self.extent)


Expand Down Expand Up @@ -152,7 +154,7 @@ def band_name(self, band: Union[str, int], allow_common=True) -> str:
return self.band_names[band]
raise ValueError("Invalid band name/index {b!r}. Valid names: {n!r}".format(b=band, n=self.band_names))

def filter_bands(self, bands: List[Union[int, str]]) -> 'BandDimension':
def filter_bands(self, bands: List[Union[int, str]]) -> BandDimension:
"""
Construct new BandDimension with subset of bands,
based on given band indices or (common) names
Expand All @@ -162,7 +164,7 @@ def filter_bands(self, bands: List[Union[int, str]]) -> 'BandDimension':
bands=[self.bands[self.band_index(b)] for b in bands]
)

def append_band(self, band: Band) -> 'BandDimension':
def append_band(self, band: Band) -> BandDimension:
"""Create new BandDimension with appended band."""
if band.name in self.band_names:
raise ValueError("Duplicate band {b!r}".format(b=band))
Expand All @@ -172,7 +174,7 @@ def append_band(self, band: Band) -> 'BandDimension':
bands=self.bands + [band]
)

def rename_labels(self, target, source) -> 'Dimension':
def rename_labels(self, target, source) -> Dimension:
if source:
if len(target) != len(source):
raise ValueError(
Expand Down Expand Up @@ -230,7 +232,7 @@ def __init__(self, metadata: dict, dimensions: List[Dimension] = None):
self._temporal_dimension = dim

@classmethod
def get_or_create(cls, metadata: Union[dict, 'CollectionMetadata', None]) -> 'CollectionMetadata':
def get_or_create(cls, metadata: Union[dict, "CollectionMetadata", None]) -> CollectionMetadata:
"""Get or create CollectionMetadata from given argument."""
if isinstance(metadata, cls):
return metadata
Expand All @@ -242,7 +244,7 @@ def __eq__(self, o: Any) -> bool:

def _clone_and_update(
self, metadata: dict = None, dimensions: List[Dimension] = None, **kwargs
) -> 'CollectionMetadata':
) -> CollectionMetadata:
"""Create a new instance (of same class) with copied/updated fields."""
cls = type(self)
if dimensions == None:
Expand Down Expand Up @@ -397,7 +399,7 @@ def band_common_names(self) -> List[str]:
def get_band_index(self, band: Union[int, str]) -> int:
return self.band_dimension.band_index(band)

def filter_bands(self, band_names: List[Union[int, str]]) -> 'CollectionMetadata':
def filter_bands(self, band_names: List[Union[int, str]]) -> CollectionMetadata:
"""
Create new `CollectionMetadata` with filtered band dimension
:param band_names: list of band names/indices to keep
Expand All @@ -409,7 +411,7 @@ def filter_bands(self, band_names: List[Union[int, str]]) -> 'CollectionMetadata
for d in self._dimensions
])

def append_band(self, band: Band) -> 'CollectionMetadata':
def append_band(self, band: Band) -> CollectionMetadata:
"""
Create new `CollectionMetadata` with given band added to band dimension.
"""
Expand All @@ -419,7 +421,7 @@ def append_band(self, band: Band) -> 'CollectionMetadata':
for d in self._dimensions
])

def rename_labels(self, dimension: str, target: list, source: list = None) -> 'CollectionMetadata':
def rename_labels(self, dimension: str, target: list, source: list = None) -> CollectionMetadata:
"""
Renames the labels of the specified dimension from source to target.
Expand All @@ -436,7 +438,7 @@ def rename_labels(self, dimension: str, target: list, source: list = None) -> 'C

return self._clone_and_update(dimensions=new_dimensions)

def rename_dimension(self, source: str, target: str) -> 'CollectionMetadata':
def rename_dimension(self, source: str, target: str) -> CollectionMetadata:
"""
Rename source dimension into target, preserving other properties
"""
Expand All @@ -447,15 +449,15 @@ def rename_dimension(self, source: str, target: str) -> 'CollectionMetadata':

return self._clone_and_update(dimensions=new_dimensions)

def reduce_dimension(self, dimension_name: str) -> 'CollectionMetadata':
def reduce_dimension(self, dimension_name: str) -> CollectionMetadata:
"""Create new metadata object by collapsing/reducing a dimension."""
# TODO: option to keep reduced dimension (with a single value)?
self.assert_valid_dimension(dimension_name)
loc = self.dimension_names().index(dimension_name)
dimensions = self._dimensions[:loc] + self._dimensions[loc + 1:]
return self._clone_and_update(dimensions=dimensions)

def add_dimension(self, name: str, label: Union[str, float], type: str = None) -> 'CollectionMetadata':
def add_dimension(self, name: str, label: Union[str, float], type: str = None) -> CollectionMetadata:
"""Create new metadata object with added dimension"""
if any(d.name == name for d in self._dimensions):
raise DimensionAlreadyExistsException(f"Dimension with name {name!r} already exists")
Expand All @@ -469,7 +471,7 @@ def add_dimension(self, name: str, label: Union[str, float], type: str = None) -
dim = Dimension(type=type or "other", name=name)
return self._clone_and_update(dimensions=self._dimensions + [dim])

def drop_dimension(self, name: str = None) -> 'CollectionMetadata':
def drop_dimension(self, name: str = None) -> CollectionMetadata:
"""Drop dimension with given name"""
dimension_names = self.dimension_names()
if name not in dimension_names:
Expand Down
18 changes: 10 additions & 8 deletions openeo/rest/connection.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""
This module provides a Connection object to manage and persist settings when interacting with the OpenEO API.
"""
from __future__ import annotations

import datetime
import json
import logging
Expand Down Expand Up @@ -306,7 +308,7 @@ def _get_refresh_token_store(self) -> RefreshTokenStore:
self._refresh_token_store = RefreshTokenStore()
return self._refresh_token_store

def authenticate_basic(self, username: Optional[str] = None, password: Optional[str] = None) -> "Connection":
def authenticate_basic(self, username: Optional[str] = None, password: Optional[str] = None) -> Connection:
"""
Authenticate a user to the backend using basic username and password.
Expand Down Expand Up @@ -431,7 +433,7 @@ def _authenticate_oidc(
store_refresh_token: bool = False,
fallback_refresh_token_to_store: Optional[str] = None,
oidc_auth_renewer: Optional[OidcAuthenticator] = None,
) -> "Connection":
) -> Connection:
"""
Authenticate through OIDC and set up bearer token (based on OIDC access_token) for further requests.
"""
Expand Down Expand Up @@ -465,7 +467,7 @@ def authenticate_oidc_authorization_code(
server_address: Optional[Tuple[str, int]] = None,
webbrowser_open: Optional[Callable] = None,
store_refresh_token=False,
) -> "Connection":
) -> Connection:
"""
OpenID Connect Authorization Code Flow (with PKCE).
Expand All @@ -489,7 +491,7 @@ def authenticate_oidc_client_credentials(
client_id: Optional[str] = None,
client_secret: Optional[str] = None,
provider_id: Optional[str] = None,
) -> 'Connection':
) -> Connection:
"""
Authenticate with :ref:`OIDC Client Credentials flow <authenticate_oidc_client_credentials>`
Expand Down Expand Up @@ -528,7 +530,7 @@ def authenticate_oidc_resource_owner_password_credentials(
client_secret: Optional[str] = None,
provider_id: Optional[str] = None,
store_refresh_token: bool = False,
) -> "Connection":
) -> Connection:
"""
OpenId Connect Resource Owner Password Credentials
"""
Expand All @@ -549,7 +551,7 @@ def authenticate_oidc_refresh_token(
provider_id: Optional[str] = None,
*,
store_refresh_token: bool = False,
) -> "Connection":
) -> Connection:
"""
Authenticate with :ref:`OIDC Refresh Token flow <authenticate_oidc_client_credentials>`
Expand Down Expand Up @@ -594,7 +596,7 @@ def authenticate_oidc_device(
use_pkce: Optional[bool] = None,
max_poll_time: float = OidcDeviceAuthenticator.DEFAULT_MAX_POLL_TIME,
**kwargs,
) -> "Connection":
) -> Connection:
"""
Authenticate with the :ref:`OIDC Device Code flow <authenticate_oidc_device>`
Expand Down Expand Up @@ -1311,7 +1313,7 @@ def load_stac(
cube.metadata = metadata
return cube

def load_ml_model(self, id: Union[str, BatchJob]) -> "MlModel":
def load_ml_model(self, id: Union[str, BatchJob]) -> MlModel:
"""
Loads a machine learning model from a STAC Item.
Expand Down
Loading

0 comments on commit 346f5f3

Please sign in to comment.