diff --git a/cognite/client/_api/assets.py b/cognite/client/_api/assets.py index 9451e1b99e..1b4a0c8a09 100644 --- a/cognite/client/_api/assets.py +++ b/cognite/client/_api/assets.py @@ -232,7 +232,7 @@ def list( external_id_prefix: str = None, aggregated_properties: Sequence[str] = None, partitions: int = None, - limit: int = LIST_LIMIT_DEFAULT, + limit: Optional[int] = LIST_LIMIT_DEFAULT, ) -> AssetList: """`List assets `_ diff --git a/cognite/client/_api/functions.py b/cognite/client/_api/functions.py index a6b881c5a0..5b283987c0 100644 --- a/cognite/client/_api/functions.py +++ b/cognite/client/_api/functions.py @@ -731,7 +731,7 @@ def list( def retrieve( self, call_id: int, function_id: Optional[int] = None, function_external_id: Optional[str] = None - ) -> Union[FunctionCallList, FunctionCall, None]: + ) -> Optional[FunctionCall]: """`Retrieve a single function call by id. `_ Args: @@ -740,7 +740,7 @@ def retrieve( function_external_id (str, optional): External ID of the function on which the call was made. Returns: - Union[FunctionCallList, FunctionCall, None]: Requested function call. + Optional[FunctionCall]: Requested function call or None if not found. Examples: diff --git a/cognite/client/_api/raw.py b/cognite/client/_api/raw.py index 1dbda7f3f0..61c787b3ea 100644 --- a/cognite/client/_api/raw.py +++ b/cognite/client/_api/raw.py @@ -241,7 +241,7 @@ def delete(self, db_name: str, name: Union[str, Sequence[str]]) -> None: task_unwrap_fn=lambda task: task["json"]["items"], task_list_element_unwrap_fn=lambda el: el["name"] ) - def list(self, db_name: str, limit: int = LIST_LIMIT_DEFAULT) -> TableList: + def list(self, db_name: str, limit: Optional[int] = LIST_LIMIT_DEFAULT) -> TableList: """`List tables `_ Args: @@ -494,7 +494,7 @@ def list( min_last_updated_time: int = None, max_last_updated_time: int = None, columns: List[str] = None, - limit: int = LIST_LIMIT_DEFAULT, + limit: Optional[int] = LIST_LIMIT_DEFAULT, ) -> RowList: """`List rows in a table. `_ diff --git a/cognite/client/_api/sequences.py b/cognite/client/_api/sequences.py index ed67d5cd7c..e54d6348e5 100644 --- a/cognite/client/_api/sequences.py +++ b/cognite/client/_api/sequences.py @@ -663,11 +663,11 @@ def retrieve( column_external_ids (Optional[SequenceType[str]]): List of external id for the columns of the sequence. If 'None' is passed, all columns will be retrieved. id (int): Id of sequence. external_id (str): External id of sequence. - limit (int): Maximum number of rows to return per sequence. 10000 is the maximum limit per request. + limit (int): Maximum number of rows to return per sequence. Returns: - List of sequence data + Union[SequenceData, SequenceDataList]: SequenceData if single identifier was given, else SequenceDataList Examples: diff --git a/cognite/client/_api_client.py b/cognite/client/_api_client.py index d4064e0a57..2cfd3121c1 100644 --- a/cognite/client/_api_client.py +++ b/cognite/client/_api_client.py @@ -78,7 +78,7 @@ def __init__(self, config: ClientConfig, api_version: Optional[str], cognite_cli self._config = config self._api_version = api_version self._api_subversion = config.api_subversion - self._cognite_client = cognite_client + self._cognite_client = cognite_client # type: ignore [assignment] self._init_http_clients() self._CREATE_LIMIT = 1000 diff --git a/cognite/client/data_classes/_base.py b/cognite/client/data_classes/_base.py index 8614862a47..c5a0e85b75 100644 --- a/cognite/client/data_classes/_base.py +++ b/cognite/client/data_classes/_base.py @@ -382,7 +382,7 @@ class CogniteResourceList(Generic[T_CogniteResource], CogniteBaseList, _WithClie def __init__(self, items: List[T_CogniteResource], cognite_client: Optional[CogniteClient] = None): super().__init__(items) - self._cognite_client = cognite_client + self._cognite_client = cognite_client # type: ignore [assignment] @classmethod def _load( # type: ignore [override] diff --git a/cognite/client/data_classes/assets.py b/cognite/client/data_classes/assets.py index 77dcffa4ae..eb8632b337 100644 --- a/cognite/client/data_classes/assets.py +++ b/cognite/client/data_classes/assets.py @@ -134,7 +134,7 @@ def __init__( self.last_updated_time = last_updated_time self.root_id = root_id self.aggregates = aggregates - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] @classmethod def _load(cls, resource: Dict, cognite_client: CogniteClient = None) -> Asset: @@ -158,7 +158,10 @@ def parent(self) -> Asset: """ if self.parent_id is None: raise ValueError("parent_id is None") - return self._cognite_client.assets.retrieve(id=self.parent_id) + return self._cognite_client.assets.retrieve_multiple( + ids=[self.parent_id], + ignore_unknown_ids=False, + )[0] def children(self) -> AssetList: """Returns the children of this asset. @@ -166,6 +169,7 @@ def children(self) -> AssetList: Returns: AssetList: The requested assets """ + assert self.id is not None return self._cognite_client.assets.list(parent_ids=[self.id], limit=None) def subtree(self, depth: int = None) -> AssetList: @@ -185,6 +189,7 @@ def time_series(self, **kwargs: Any) -> TimeSeriesList: Returns: TimeSeriesList: All time series related to this asset. """ + assert self.id is not None return self._cognite_client.time_series.list(asset_ids=[self.id], **kwargs) def sequences(self, **kwargs: Any) -> SequenceList: @@ -193,6 +198,7 @@ def sequences(self, **kwargs: Any) -> SequenceList: Returns: SequenceList: All sequences related to this asset. """ + assert self.id is not None return self._cognite_client.sequences.list(asset_ids=[self.id], **kwargs) def events(self, **kwargs: Any) -> EventList: @@ -202,6 +208,7 @@ def events(self, **kwargs: Any) -> EventList: EventList: All events related to this asset. """ + assert self.id is not None return self._cognite_client.events.list(asset_ids=[self.id], **kwargs) def files(self, **kwargs: Any) -> FileMetadataList: @@ -210,6 +217,7 @@ def files(self, **kwargs: Any) -> FileMetadataList: Returns: FileMetadataList: Metadata about all files related to this asset. """ + assert self.id is not None return self._cognite_client.files.list(asset_ids=[self.id], **kwargs) def dump(self, camel_case: bool = False) -> Dict[str, Any]: diff --git a/cognite/client/data_classes/contextualization.py b/cognite/client/data_classes/contextualization.py index 61c4df1cf6..c4c9c01a52 100644 --- a/cognite/client/data_classes/contextualization.py +++ b/cognite/client/data_classes/contextualization.py @@ -98,7 +98,7 @@ def __init__( self.job_token = job_token self._result: Optional[Dict[str, Any]] = None self._status_path = status_path - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] def update_status(self) -> str: """Updates the model status and returns it""" @@ -207,7 +207,7 @@ def __init__( self.name = name self.description = description self.external_id = external_id - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] def __str__(self) -> str: return f"{self.__class__.__name__}(id={self.id}, status={self.status}, error={self.error_message})" @@ -369,7 +369,7 @@ def __init__( self.page = page self.png_url = png_url self.svg_url = svg_url - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] class DiagramConvertPageList(CogniteResourceList): @@ -387,7 +387,7 @@ def __init__( self.file_id = file_id self.file_external_id = file_external_id self.results = results - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] def __len__(self) -> int: assert self.results @@ -461,7 +461,7 @@ def __init__( self.annotations = annotations self.error_message = error_message self.page_range = page_range - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] def to_pandas(self, camel_case: bool = False) -> pandas.DataFrame: # type: ignore[override] """Convert the instance into a pandas DataFrame. @@ -607,7 +607,7 @@ def __init__(self, job_ids: List[int], cognite_client: CogniteClient = None): "Breaking changes can happen in between patch versions." ) - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client: CogniteClient = cognite_client # type: ignore [assignment] if not job_ids: raise ValueError("You need to specify job_ids") self.job_ids = job_ids @@ -720,7 +720,7 @@ def __init__( self.predictions = self._process_predictions_dict(predictions) if isinstance(predictions, Dict) else predictions self._predictions_dict = predictions # The "raw" predictions dict returned by the endpoint - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] @classmethod def _load(cls, resource: Dict, cognite_client: CogniteClient = None) -> VisionExtractItem: diff --git a/cognite/client/data_classes/data_sets.py b/cognite/client/data_classes/data_sets.py index b0274b532c..22d767cf71 100644 --- a/cognite/client/data_classes/data_sets.py +++ b/cognite/client/data_classes/data_sets.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Dict, List, Union, cast +from typing import TYPE_CHECKING, Any, Dict, List, Union from cognite.client.data_classes._base import ( CogniteFilter, @@ -54,7 +54,7 @@ def __init__( self.id = id self.created_time = created_time self.last_updated_time = last_updated_time - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] class DataSetFilter(CogniteFilter): diff --git a/cognite/client/data_classes/events.py b/cognite/client/data_classes/events.py index c514cc7258..4a10772e51 100644 --- a/cognite/client/data_classes/events.py +++ b/cognite/client/data_classes/events.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Dict, List, Sequence, Union, cast +from typing import TYPE_CHECKING, Any, Dict, List, Sequence, Union from cognite.client.data_classes._base import ( CogniteFilter, @@ -89,7 +89,7 @@ def __init__( self.id = id self.last_updated_time = last_updated_time self.created_time = created_time - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] class EventFilter(CogniteFilter): diff --git a/cognite/client/data_classes/extractionpipelines.py b/cognite/client/data_classes/extractionpipelines.py index abd2ed01e7..d69b21f110 100644 --- a/cognite/client/data_classes/extractionpipelines.py +++ b/cognite/client/data_classes/extractionpipelines.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Dict, List, Sequence, Union, cast +from typing import TYPE_CHECKING, Any, Dict, List, Sequence, Union from cognite.client.data_classes._base import ( CogniteFilter, @@ -109,7 +109,7 @@ def __init__( self.created_time = created_time self.last_updated_time = last_updated_time self.created_by = created_by - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] @classmethod def _load(cls, resource: Dict, cognite_client: CogniteClient = None) -> ExtractionPipeline: @@ -223,7 +223,7 @@ def __init__( self.status = status self.message = message self.created_time = created_time - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] @classmethod def _load(cls, resource: Dict, cognite_client: CogniteClient = None) -> ExtractionPipelineRun: @@ -309,7 +309,7 @@ def __init__( self.revision = revision self.description = description self.created_time = created_time - self._cognite_client = cognite_client + self._cognite_client = cognite_client # type: ignore [assignment] class ExtractionPipelineConfig(ExtractionPipelineConfigRevision): diff --git a/cognite/client/data_classes/files.py b/cognite/client/data_classes/files.py index 0ed847e9b8..5a78d7646a 100644 --- a/cognite/client/data_classes/files.py +++ b/cognite/client/data_classes/files.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Dict, List, Sequence, Union, cast +from typing import TYPE_CHECKING, Any, Dict, List, Sequence, Union from cognite.client.data_classes._base import ( CogniteFilter, @@ -87,7 +87,7 @@ def __init__( self.uploaded_time = uploaded_time self.created_time = created_time self.last_updated_time = last_updated_time - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] @classmethod def _load(cls, resource: Dict, cognite_client: CogniteClient = None) -> FileMetadata: diff --git a/cognite/client/data_classes/functions.py b/cognite/client/data_classes/functions.py index 6bf7aa0925..f8af1e47b0 100644 --- a/cognite/client/data_classes/functions.py +++ b/cognite/client/data_classes/functions.py @@ -81,7 +81,7 @@ def __init__( self.runtime_version = runtime_version self.metadata = metadata self.error = error - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] def call(self, data: Optional[Dict] = None, wait: bool = True) -> FunctionCall: """`Call this particular function. `_ @@ -143,14 +143,14 @@ def list_schedules(self, limit: Optional[int] = LIST_LIMIT_DEFAULT) -> FunctionS return (schedules_by_external_id + schedules_by_id)[:limit] - def retrieve_call(self, id: int) -> FunctionCall: + def retrieve_call(self, id: int) -> Optional[FunctionCall]: """`Retrieve call by id. `_ Args: id (int): ID of the call. Returns: - FunctionCall: Function call. + Optional[FunctionCall]: Requested function call or None if not found. """ return self._cognite_client.functions.calls.retrieve(call_id=id, function_id=self.id) @@ -241,7 +241,7 @@ def __init__( self.created_time = created_time self.session_id = session_id self.when = when - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] def get_input_data(self) -> Optional[dict]: """ @@ -251,6 +251,7 @@ def get_input_data(self) -> Optional[dict]: Optional[Dict]: Input data to the associated function or None if not set. This data is passed deserialized into the function through the data argument. """ + assert self.id is not None return self._cognite_client.functions.schedules.get_input_data(id=self.id) @@ -312,7 +313,7 @@ def __init__( self.schedule_id = schedule_id self.error = error self.function_id = function_id - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] def get_response(self) -> Dict: """Retrieve the response from this function call. @@ -320,6 +321,7 @@ def get_response(self) -> Dict: Returns: Response from the function call. """ + assert self.id is not None return self._cognite_client.functions.calls.get_response(call_id=self.id, function_id=self.function_id) def get_logs(self) -> FunctionCallLog: @@ -328,6 +330,7 @@ def get_logs(self) -> FunctionCallLog: Returns: FunctionCallLog: Log for the function call. """ + assert self.id is not None return self._cognite_client.functions.calls.get_logs(call_id=self.id, function_id=self.function_id) def update(self) -> None: @@ -336,7 +339,10 @@ def update(self) -> None: Returns: None """ + assert self.id is not None latest = self._cognite_client.functions.calls.retrieve(call_id=self.id, function_id=self.function_id) + if latest is None: + raise RuntimeError("Unable to update the function call object") self.status = latest.status self.end_time = latest.end_time self.error = latest.error diff --git a/cognite/client/data_classes/geospatial.py b/cognite/client/data_classes/geospatial.py index 21509e0a62..707022c349 100644 --- a/cognite/client/data_classes/geospatial.py +++ b/cognite/client/data_classes/geospatial.py @@ -36,7 +36,7 @@ def __init__( self.last_updated_time = last_updated_time self.properties = properties self.search_spec = search_spec - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] @classmethod def _load(cls, resource: Union[str, Dict[str, Any]], cognite_client: CogniteClient = None) -> FeatureType: @@ -76,7 +76,7 @@ def __init__( self.external_id = external_id self.add = add if add is not None else PropertyAndSearchSpec() self.remove = remove if remove is not None else PropertyAndSearchSpec() - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] @dataclasses.dataclass @@ -105,7 +105,7 @@ def __init__(self, external_id: str = None, cognite_client: CogniteClient = None self.external_id = external_id for key in properties: setattr(self, key, properties[key]) - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] @classmethod def _load(cls, resource: Union[str, Dict[str, Any]], cognite_client: CogniteClient = None) -> Feature: @@ -288,7 +288,7 @@ class FeatureAggregate(CogniteResource): """A result of aggregating features in geospatial api.""" def __init__(self, cognite_client: CogniteClient = None): - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] @classmethod def _load(cls, resource: Union[str, Dict[str, Any]], cognite_client: CogniteClient = None) -> FeatureAggregate: @@ -314,7 +314,7 @@ def __init__( self.srid = srid self.wkt = wkt self.proj_string = proj_string - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] @classmethod def _load( @@ -401,7 +401,7 @@ class GeospatialComputedItem(CogniteResource): def __init__(self, resource: Dict[str, Any], cognite_client: CogniteClient = None): self.resource = resource - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] @classmethod def _load( @@ -426,7 +426,7 @@ class GeospatialComputedResponse(CogniteResource): def __init__(self, computed_item_list: GeospatialComputedItemList, cognite_client: CogniteClient = None): self.items = computed_item_list - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] @classmethod def _load( diff --git a/cognite/client/data_classes/iam.py b/cognite/client/data_classes/iam.py index c203fbf603..bbc847dcaa 100644 --- a/cognite/client/data_classes/iam.py +++ b/cognite/client/data_classes/iam.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Dict, List, Optional, cast +from typing import TYPE_CHECKING, Any, Dict, List, Optional from cognite.client.data_classes._base import CogniteResource, CogniteResourceList, CogniteResponse from cognite.client.utils._auxiliary import basic_obj_dump @@ -39,7 +39,7 @@ def __init__( self.id = id self.is_deleted = is_deleted self.deleted_time = deleted_time - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] class GroupList(CogniteResourceList): @@ -58,7 +58,7 @@ class SecurityCategory(CogniteResource): def __init__(self, name: str = None, id: int = None, cognite_client: CogniteClient = None): self.name = name self.id = id - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] class SecurityCategoryList(CogniteResourceList): @@ -140,7 +140,7 @@ def __init__( self.status = status self.nonce = nonce self.client_id = client_id - self._cognite_client = cognite_client + self._cognite_client = cognite_client # type: ignore [assignment] class Session(CogniteResource): @@ -171,7 +171,7 @@ def __init__( self.creation_time = creation_time self.expiration_time = expiration_time self.client_id = client_id - self._cognite_client = cognite_client + self._cognite_client = cognite_client # type: ignore [assignment] class SessionList(CogniteResourceList): diff --git a/cognite/client/data_classes/labels.py b/cognite/client/data_classes/labels.py index fbeb0d3709..c4429e25a3 100644 --- a/cognite/client/data_classes/labels.py +++ b/cognite/client/data_classes/labels.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Union, cast +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Union from cognite.client.data_classes._base import ( CogniteFilter, @@ -40,7 +40,7 @@ def __init__( self.description = description self.created_time = created_time self.data_set_id = data_set_id - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] class LabelDefinitionFilter(CogniteFilter): diff --git a/cognite/client/data_classes/raw.py b/cognite/client/data_classes/raw.py index 181ae1bd76..ae01e889f3 100644 --- a/cognite/client/data_classes/raw.py +++ b/cognite/client/data_classes/raw.py @@ -1,7 +1,7 @@ from __future__ import annotations from collections import OrderedDict -from typing import TYPE_CHECKING, Any, Dict, Optional, Union, cast +from typing import TYPE_CHECKING, Any, Dict, Optional, Union, cast, overload from cognite.client import utils from cognite.client.data_classes._base import CogniteResource, CogniteResourceList @@ -32,7 +32,7 @@ def __init__( self.key = key self.columns = columns self.last_updated_time = last_updated_time - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] def to_pandas(self) -> pandas.DataFrame: # type: ignore[override] """Convert the instance into a pandas DataFrame. @@ -69,11 +69,19 @@ class Table(CogniteResource): def __init__(self, name: str = None, created_time: int = None, cognite_client: CogniteClient = None): self.name = name self.created_time = created_time - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] self._db_name: Optional[str] = None - def rows(self, key: str = None, limit: int = None) -> Union[Row, RowList]: + @overload + def rows(self, key: str, limit: int = None) -> Optional[Row]: + ... + + @overload + def rows(self, key: None, limit: int = None) -> RowList: + ... + + def rows(self, key: str = None, limit: int = None) -> Union[None, Row, RowList]: """Get the rows in this table. Args: @@ -83,7 +91,12 @@ def rows(self, key: str = None, limit: int = None) -> Union[Row, RowList]: Returns: Union[Row, RowList]: List of tables in this database. """ - if key: + if self._db_name is None: + raise ValueError("Table is not linked to a database, did you instantiate it yourself?") + elif self.name is None: + raise ValueError("Table 'name' is missing") + + if key is not None: return self._cognite_client.raw.rows.retrieve(db_name=self._db_name, table_name=self.name, key=key) return self._cognite_client.raw.rows.list(db_name=self._db_name, table_name=self.name, limit=limit) @@ -104,7 +117,7 @@ class Database(CogniteResource): def __init__(self, name: str = None, created_time: int = None, cognite_client: CogniteClient = None): self.name = name self.created_time = created_time - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] def tables(self, limit: int = None) -> TableList: """Get the tables in this database. @@ -115,6 +128,8 @@ def tables(self, limit: int = None) -> TableList: Returns: TableList: List of tables in this database. """ + if self.name is None: + raise ValueError("Unable to list tables, 'name' is not set on instance") return self._cognite_client.raw.tables.list(db_name=self.name, limit=limit) diff --git a/cognite/client/data_classes/relationships.py b/cognite/client/data_classes/relationships.py index e3587ace75..a21302c204 100644 --- a/cognite/client/data_classes/relationships.py +++ b/cognite/client/data_classes/relationships.py @@ -1,7 +1,7 @@ from __future__ import annotations import copy -from typing import TYPE_CHECKING, Any, Dict, List, Optional, Type, Union, cast +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Type, Union from typing import Sequence as SequenceType from cognite.client.data_classes._base import ( @@ -78,7 +78,7 @@ def __init__( self.created_time = created_time self.last_updated_time = last_updated_time self.labels = Label._load_list(labels) - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] def _validate_resource_types(self) -> Relationship: rel = copy.copy(self) diff --git a/cognite/client/data_classes/sequences.py b/cognite/client/data_classes/sequences.py index 16cb915107..82518ed334 100644 --- a/cognite/client/data_classes/sequences.py +++ b/cognite/client/data_classes/sequences.py @@ -2,7 +2,7 @@ import json import math -from typing import TYPE_CHECKING, Any, Dict, Generator, List, Tuple, Union, cast +from typing import TYPE_CHECKING, Any, Dict, Generator, List, Optional, Tuple, Union, cast from typing import Sequence as SequenceType from cognite.client import utils @@ -68,16 +68,16 @@ def __init__( self.created_time = created_time self.last_updated_time = last_updated_time self.data_set_id = data_set_id - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] - def rows(self, start: int, end: int) -> List[dict]: + def rows(self, start: int, end: Optional[int]) -> SequenceData: """Retrieves rows from this sequence. Returns: List of sequence data. """ identifier = Identifier.load(self.id, self.external_id).as_dict() - return self._cognite_client.sequences.data.retrieve(**identifier, start=start, end=end) + return cast(SequenceData, self._cognite_client.sequences.data.retrieve(**identifier, start=start, end=end)) @property def column_external_ids(self) -> List[str]: diff --git a/cognite/client/data_classes/templates.py b/cognite/client/data_classes/templates.py index a84eab533a..afaa5c4cea 100644 --- a/cognite/client/data_classes/templates.py +++ b/cognite/client/data_classes/templates.py @@ -2,7 +2,7 @@ import json from collections import UserDict -from typing import TYPE_CHECKING, Any, Dict, List, Optional, Type, Union, cast +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Type, Union from cognite.client.data_classes._base import CogniteObjectUpdate, CogniteResource, CogniteResourceList, CogniteUpdate from cognite.client.utils._text import to_camel_case, to_snake_case @@ -42,7 +42,7 @@ def __init__( self.data_set_id = data_set_id self.created_time = created_time self.last_updated_time = last_updated_time - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] class TemplateGroupList(CogniteResourceList): @@ -78,7 +78,7 @@ def __init__( self.conflict_mode = conflict_mode self.created_time = created_time self.last_updated_time = last_updated_time - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] class TemplateGroupVersionList(CogniteResourceList): @@ -95,7 +95,7 @@ class ConstantResolver(CogniteResource): def __init__(self, value: Any = None, cognite_client: CogniteClient = None): self.type = "constant" self.value = value - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] class RawResolver(CogniteResource): @@ -121,7 +121,7 @@ def __init__( self.table_name = table_name self.row_key = row_key self.column_name = column_name - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] class SyntheticTimeSeriesResolver(CogniteResource): @@ -156,7 +156,7 @@ def __init__( self.is_step = is_step self.is_string = is_string self.unit = unit - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] class ViewResolver(CogniteResource): @@ -173,7 +173,7 @@ def __init__( self.type = "view" self.external_id = external_id self.input = input - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] FieldResolvers = Union[ConstantResolver, RawResolver, SyntheticTimeSeriesResolver, str, ViewResolver] @@ -207,7 +207,7 @@ def __init__( self.data_set_id = data_set_id self.created_time = created_time self.last_updated_time = last_updated_time - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] field_resolver_mapper: Dict[str, Type[CogniteResource]] = { "constant": ConstantResolver, @@ -318,7 +318,7 @@ def __init__( self.type = type self.filter = filter self.mappings = mappings - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] class View(CogniteResource): @@ -345,7 +345,7 @@ def __init__( self.data_set_id = data_set_id self.created_time = created_time self.last_updated_time = last_updated_time - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] def dump(self, camel_case: bool = False) -> Dict[str, Any]: """Dump the instance into a json serializable Python data type. @@ -393,7 +393,7 @@ def _load(cls, resource: Dict, cognite_client: CogniteClient = None) -> View: class ViewResolveItem(UserDict, CogniteResource): def __init__(self, data: Dict[str, Any], cognite_client: CogniteClient = None) -> None: super().__init__(data) - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] def dump(self, camel_case: bool = False) -> Dict[str, Any]: return self.data @@ -417,14 +417,14 @@ def __init__( self.message = message self.path = path self.locations = locations - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] class GraphQlResponse(CogniteResource): def __init__(self, data: Any = None, errors: List[GraphQlError] = None, cognite_client: CogniteClient = None): self.data = data self.errors = errors - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] class TemplateInstanceList(CogniteResourceList): diff --git a/cognite/client/data_classes/three_d.py b/cognite/client/data_classes/three_d.py index 0de1af78e9..55c346d2d2 100644 --- a/cognite/client/data_classes/three_d.py +++ b/cognite/client/data_classes/three_d.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Dict, List, Union, cast +from typing import TYPE_CHECKING, Any, Dict, List, Union from cognite.client.data_classes._base import ( CogniteLabelUpdate, @@ -74,7 +74,7 @@ def __init__( self.id = id self.created_time = created_time self.metadata = metadata - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] class ThreeDModelUpdate(CogniteUpdate): @@ -172,7 +172,7 @@ def __init__( self.thumbnail_url = thumbnail_url self.asset_mapping_count = asset_mapping_count self.created_time = created_time - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] @classmethod def _load(cls, resource: Dict, cognite_client: CogniteClient = None) -> ThreeDModelRevision: @@ -277,7 +277,7 @@ def __init__( self.subtree_size = subtree_size self.properties = properties self.bounding_box = bounding_box - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] @classmethod def _load(cls, resource: Dict, cognite_client: CogniteClient = None) -> ThreeDNode: @@ -315,7 +315,7 @@ def __init__( self.asset_id = asset_id self.tree_index = tree_index self.subtree_size = subtree_size - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] class ThreeDAssetMappingList(CogniteResourceList): diff --git a/cognite/client/data_classes/time_series.py b/cognite/client/data_classes/time_series.py index c94330e1e5..b56aeee39f 100644 --- a/cognite/client/data_classes/time_series.py +++ b/cognite/client/data_classes/time_series.py @@ -1,7 +1,7 @@ from __future__ import annotations from datetime import datetime -from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Union, cast +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Union from cognite.client.data_classes._base import ( CogniteFilter, @@ -76,7 +76,7 @@ def __init__( self.created_time = created_time self.last_updated_time = last_updated_time self.legacy_name = legacy_name - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] def count(self) -> int: """Returns the number of datapoints in this time series. @@ -99,7 +99,7 @@ def count(self) -> int: dps = self._cognite_client.time_series.data.retrieve( **identifier, start=MIN_TIMESTAMP_MS, end=MAX_TIMESTAMP_MS + 1, aggregates="count", granularity="100d" ) - return sum(dps.count) + return sum(dps.count) # type: ignore [union-attr, arg-type] def latest(self, before: Union[int, str, datetime] = None) -> Optional[Datapoint]: """Returns the latest datapoint in this time series. If empty, returns None. @@ -134,7 +134,7 @@ def asset(self) -> Asset: """ if self.asset_id is None: raise ValueError("asset_id is None") - return self._cognite_client.assets.retrieve(id=self.asset_id) + return self._cognite_client.assets.retrieve_multiple(ids=[self.asset_id], ignore_unknown_ids=False)[0] class TimeSeriesFilter(CogniteFilter): diff --git a/cognite/client/data_classes/transformations/__init__.py b/cognite/client/data_classes/transformations/__init__.py index 3e0566460a..6d42c2dd0e 100644 --- a/cognite/client/data_classes/transformations/__init__.py +++ b/cognite/client/data_classes/transformations/__init__.py @@ -1,7 +1,7 @@ from __future__ import annotations from abc import abstractmethod -from typing import TYPE_CHECKING, Any, Awaitable, Dict, List, Optional, Union, cast +from typing import TYPE_CHECKING, Any, Awaitable, Dict, List, Optional, Union from cognite.client.data_classes._base import ( CogniteFilter, @@ -153,7 +153,7 @@ def __init__( self.source_session = source_session self.destination_session = destination_session self.tags = tags - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] def copy(self) -> Transformation: return Transformation( @@ -211,6 +211,7 @@ def try_get_or_create_nonce(oidc_credentials: Optional[OidcCredentials]) -> Opti credentials = None try: session = self._cognite_client.iam.sessions.create(credentials) + assert session.id is not None and session.nonce is not None ret = NonceCredentials(session.id, session.nonce, self._cognite_client._config.project) sessions_cache[key] = ret except Exception: @@ -484,7 +485,7 @@ def __init__( ) -> None: self.schema = schema self.results = results - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] @classmethod def _load(cls, resource: Dict, cognite_client: CogniteClient = None) -> TransformationPreviewResult: diff --git a/cognite/client/data_classes/transformations/jobs.py b/cognite/client/data_classes/transformations/jobs.py index 37cfa1a073..a940aee9b5 100644 --- a/cognite/client/data_classes/transformations/jobs.py +++ b/cognite/client/data_classes/transformations/jobs.py @@ -3,7 +3,7 @@ import asyncio import time from enum import Enum -from typing import TYPE_CHECKING, Dict, Optional, cast +from typing import TYPE_CHECKING, Dict, Optional from cognite.client.data_classes._base import CogniteFilter, CogniteResource, CogniteResourceList from cognite.client.data_classes.transformations.common import TransformationDestination, _load_destination_dct @@ -40,7 +40,7 @@ def __init__( self.timestamp = timestamp self.name = name self.count = count - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] @classmethod def _load(cls, resource: Dict, cognite_client: CogniteClient = None) -> TransformationJobMetric: @@ -110,11 +110,15 @@ def __init__( self.started_time = started_time self.finished_time = finished_time self.last_seen_time = last_seen_time - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] def update(self) -> None: """`Get updated job status.`""" + if self.id is None: + raise ValueError("Unable to update, TransformationJob is missing 'id'") updated = self._cognite_client.transformations.jobs.retrieve(id=self.id) + if updated is None: + raise RuntimeError("Unable to update the transformation. Has it been deleted?") self.status = updated.status self.error = updated.error self.started_time = updated.started_time diff --git a/cognite/client/data_classes/transformations/notifications.py b/cognite/client/data_classes/transformations/notifications.py index 8f8c3e87e0..73099a5091 100644 --- a/cognite/client/data_classes/transformations/notifications.py +++ b/cognite/client/data_classes/transformations/notifications.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Optional, cast +from typing import TYPE_CHECKING, Optional from cognite.client.data_classes._base import CogniteFilter, CogniteResource, CogniteResourceList @@ -37,7 +37,7 @@ def __init__( self.destination = destination self.created_time = created_time self.last_updated_time = last_updated_time - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] def __hash__(self) -> int: return hash(self.id) diff --git a/cognite/client/data_classes/transformations/schedules.py b/cognite/client/data_classes/transformations/schedules.py index 8b13b71c7c..a0632aafbc 100644 --- a/cognite/client/data_classes/transformations/schedules.py +++ b/cognite/client/data_classes/transformations/schedules.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, cast +from typing import TYPE_CHECKING, Any from cognite.client.data_classes._base import ( CognitePrimitiveUpdate, @@ -42,7 +42,7 @@ def __init__( self.last_updated_time = last_updated_time self.interval = interval self.is_paused = is_paused - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] def __hash__(self) -> int: return hash(self.id) diff --git a/cognite/client/data_classes/transformations/schema.py b/cognite/client/data_classes/transformations/schema.py index c13294e66b..4f9f6330c0 100644 --- a/cognite/client/data_classes/transformations/schema.py +++ b/cognite/client/data_classes/transformations/schema.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Dict, cast +from typing import TYPE_CHECKING, Dict from cognite.client.data_classes._base import CogniteResource, CogniteResourceList from cognite.client.utils._text import convert_all_keys_to_snake_case @@ -52,7 +52,7 @@ def __init__( self.sql_type = sql_type self.type = type self.nullable = nullable - self._cognite_client = cast("CogniteClient", cognite_client) + self._cognite_client = cognite_client # type: ignore [assignment] @classmethod def _load(cls, resource: Dict, cognite_client: CogniteClient = None) -> TransformationSchemaColumn: diff --git a/tests/tests_unit/test_api_client.py b/tests/tests_unit/test_api_client.py index b535aeb7a1..f7e1c1d447 100644 --- a/tests/tests_unit/test_api_client.py +++ b/tests/tests_unit/test_api_client.py @@ -214,7 +214,7 @@ def __init__(self, x=None, y=None, id=None, external_id=None, cognite_client=Non self.y = y self.id = id self.external_id = external_id - self._cognite_client = cognite_client + self._cognite_client = cognite_client # type: ignore [assignment] class SomeResourceList(CogniteResourceList): diff --git a/tests/tests_unit/test_base.py b/tests/tests_unit/test_base.py index 34a3340762..2da23c1223 100644 --- a/tests/tests_unit/test_base.py +++ b/tests/tests_unit/test_base.py @@ -40,7 +40,7 @@ def __init__(self, var_a=None, var_b=None, id=None, external_id=None, cognite_cl self.var_b = var_b self.id = id self.external_id = external_id - self._cognite_client = cognite_client + self._cognite_client = cognite_client # type: ignore [assignment] def use(self): return self._cognite_client diff --git a/tests/tests_unit/test_data_classes/test_assets.py b/tests/tests_unit/test_data_classes/test_assets.py index 93e0909ec2..1fe9e04b66 100644 --- a/tests/tests_unit/test_data_classes/test_assets.py +++ b/tests/tests_unit/test_data_classes/test_assets.py @@ -54,11 +54,11 @@ def test_get_files(self, cognite_client): assert cognite_client.files.list.call_count == 1 def test_get_parent(self, cognite_client): - cognite_client.assets.retrieve = mock.MagicMock() + cognite_client.assets.retrieve_multiple = mock.MagicMock() a1 = Asset(parent_id=1, cognite_client=cognite_client) a1.parent() - assert cognite_client.assets.retrieve.call_args == call(id=1) - assert cognite_client.assets.retrieve.call_count == 1 + assert cognite_client.assets.retrieve_multiple.call_args == call(id=1) + assert cognite_client.assets.retrieve_multiple.call_count == 1 def test_get_children(self, cognite_client): cognite_client.assets.list = mock.MagicMock()