Skip to content

Commit

Permalink
isinstance checks should not use generics from typing (#1407)
Browse files Browse the repository at this point in the history
  • Loading branch information
HaydenCognite authored Oct 5, 2023
1 parent 4cd59a1 commit 2372eeb
Show file tree
Hide file tree
Showing 11 changed files with 36 additions and 40 deletions.
6 changes: 3 additions & 3 deletions cognite/client/_api/raw.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import annotations

from typing import TYPE_CHECKING, Any, Iterator, List, Sequence, cast, overload
from typing import TYPE_CHECKING, Any, Iterator, Sequence, cast, overload

from cognite.client import utils
from cognite.client._api_client import APIClient
Expand Down Expand Up @@ -495,12 +495,12 @@ def retrieve(self, db_name: str, table_name: str, key: str) -> Row | None:
def _make_columns_param(self, columns: list[str] | None) -> str | None:
if columns is None:
return None
if not isinstance(columns, List):
if not isinstance(columns, list):
raise ValueError("Expected a list for argument columns")
if len(columns) == 0:
return ","
else:
return ",".join([str(x) for x in columns])
return ",".join(str(x) for x in columns)

def retrieve_dataframe(
self,
Expand Down
4 changes: 2 additions & 2 deletions cognite/client/_api/synthetic_time_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import re
from datetime import datetime
from typing import TYPE_CHECKING, Any, List, Sequence, cast
from typing import TYPE_CHECKING, Any, Sequence, cast

import cognite.client.utils._time
from cognite.client import utils
Expand Down Expand Up @@ -94,7 +94,7 @@ def query(

return (
DatapointsList(datapoints_summary.results, cognite_client=self._cognite_client)
if isinstance(expressions, List)
if isinstance(expressions, list)
else datapoints_summary.results[0]
)

Expand Down
6 changes: 3 additions & 3 deletions cognite/client/_api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -636,7 +636,7 @@ def _aggregate(
utils._auxiliary.assert_type(fields, "fields", [list], allow_none=True)
if isinstance(filter, CogniteFilter):
dumped_filter = filter.dump(camel_case=True)
elif isinstance(filter, Dict):
elif isinstance(filter, dict):
dumped_filter = convert_all_keys_to_camel_case(filter)
else:
dumped_filter = {}
Expand Down Expand Up @@ -748,7 +748,7 @@ def _advanced_aggregate(
utils._auxiliary.assert_type(filter, "filter", [dict, CogniteFilter], allow_none=False)
if isinstance(filter, CogniteFilter):
dumped_filter = filter.dump(camel_case=True)
elif isinstance(filter, Dict):
elif isinstance(filter, dict):
dumped_filter = convert_all_keys_to_camel_case(filter)
else:
raise ValueError(f"Unknown filter format: {filter}")
Expand Down Expand Up @@ -1164,7 +1164,7 @@ def _raise_api_error(cls, res: Response, payload: dict) -> NoReturn:
error = res.json()["error"]
if isinstance(error, str):
msg = error
elif isinstance(error, Dict):
elif isinstance(error, dict):
msg = error["message"]
missing = error.get("missing")
duplicated = error.get("duplicated")
Expand Down
13 changes: 6 additions & 7 deletions cognite/client/data_classes/annotation_types/images.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from __future__ import annotations

from dataclasses import dataclass
from typing import Dict

from cognite.client.data_classes.annotation_types.primitives import (
BoundingBox,
Expand All @@ -22,11 +21,11 @@ class ObjectDetection(VisionResource):
polyline: PolyLine | None = None

def __post_init__(self) -> None:
if isinstance(self.bounding_box, Dict):
if isinstance(self.bounding_box, dict):
self.bounding_box = BoundingBox(**self.bounding_box)
if isinstance(self.polygon, Dict):
if isinstance(self.polygon, dict):
self.polygon = Polygon(**self.polygon)
if isinstance(self.polyline, Dict):
if isinstance(self.polyline, dict):
self.polyline = PolyLine(**self.polyline)


Expand All @@ -37,7 +36,7 @@ class TextRegion(VisionResource):
confidence: float | None = None

def __post_init__(self) -> None:
if isinstance(self.text_region, Dict):
if isinstance(self.text_region, dict):
self.text_region = BoundingBox(**self.text_region)


Expand All @@ -49,7 +48,7 @@ class AssetLink(VisionResource):
confidence: float | None = None

def __post_init__(self) -> None:
if isinstance(self.text_region, Dict):
if isinstance(self.text_region, dict):
self.text_region = BoundingBox(**self.text_region)
if isinstance(self.asset_ref, Dict):
if isinstance(self.asset_ref, dict):
self.asset_ref = CdfResourceRef(**self.asset_ref)
5 changes: 2 additions & 3 deletions cognite/client/data_classes/assets.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,9 +162,8 @@ def __init__(
@classmethod
def _load(cls, resource: dict | str, cognite_client: CogniteClient | None = None) -> Asset:
instance = super()._load(resource, cognite_client)
if isinstance(resource, Dict):
if instance.aggregates is not None:
instance.aggregates = AggregateResultItem(**instance.aggregates)
if isinstance(resource, dict) and instance.aggregates is not None:
instance.aggregates = AggregateResultItem(**instance.aggregates)
instance.labels = Label._load_list(instance.labels)
if instance.geo_location is not None:
instance.geo_location = GeoLocation._load(instance.geo_location)
Expand Down
6 changes: 3 additions & 3 deletions cognite/client/data_classes/contextualization.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import warnings
from dataclasses import dataclass
from enum import Enum
from typing import TYPE_CHECKING, Any, Dict, Sequence, Type, TypeVar, Union, cast
from typing import TYPE_CHECKING, Any, Sequence, Type, TypeVar, Union, cast

from requests.utils import CaseInsensitiveDict

Expand Down Expand Up @@ -728,7 +728,7 @@ def __init__(
self.file_id = file_id
self.file_external_id = file_external_id
self.error_message = error_message
self.predictions = self._process_predictions_dict(predictions) if isinstance(predictions, Dict) else predictions
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)
Expand All @@ -745,7 +745,7 @@ def _load(cls, resource: dict | str, cognite_client: CogniteClient | None = None
def dump(self, camel_case: bool = False) -> dict[str, Any]:
item_dump = super().dump(camel_case=camel_case)
# Replace the loaded VisionExtractPredictions with its corresponding dict representation
if "predictions" in item_dump and isinstance(self._predictions_dict, Dict):
if "predictions" in item_dump and isinstance(self._predictions_dict, dict):
item_dump["predictions"] = (
self._predictions_dict if camel_case else self._resource_to_snake_case(self._predictions_dict)
)
Expand Down
10 changes: 5 additions & 5 deletions cognite/client/data_classes/templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import json
from collections import UserDict
from typing import TYPE_CHECKING, Any, ClassVar, Dict, Union, cast
from typing import TYPE_CHECKING, Any, ClassVar, Union, cast

from cognite.client.data_classes._base import (
CogniteObjectUpdate,
Expand Down Expand Up @@ -259,15 +259,15 @@ def dump(self, camel_case: bool = False) -> dict[str, Any]:
@staticmethod
def _encode_field_resolvers(field_resolvers: dict[str, FieldResolvers], camel_case: bool) -> dict[str, Any]:
return {
key: value.dump(camel_case=camel_case) if not isinstance(value, str) else value
key: value if isinstance(value, str) else value.dump(camel_case=camel_case)
for key, value in field_resolvers.items()
}

@classmethod
def _load(cls, resource: dict | str, cognite_client: CogniteClient | None = None) -> TemplateInstance:
if isinstance(resource, str):
return cls._load(json.loads(resource), cognite_client=cognite_client)
elif isinstance(resource, Dict):
elif isinstance(resource, dict):
instance = cls(cognite_client=cognite_client)
for key, value in resource.items():
snake_case_key = to_snake_case(key)
Expand Down Expand Up @@ -401,7 +401,7 @@ def resolve_nested_classes(value: CogniteResource | dict, camel_case: bool) -> d
def _load(cls, resource: dict | str, cognite_client: CogniteClient | None = None) -> View:
if isinstance(resource, str):
return cls._load(json.loads(resource), cognite_client=cognite_client)
elif isinstance(resource, Dict):
elif isinstance(resource, dict):
instance = cls(cognite_client=cognite_client)
for key, value in resource.items():
snake_case_key = to_snake_case(key)
Expand All @@ -424,7 +424,7 @@ def dump(self, camel_case: bool = False) -> dict[str, Any]:
def _load(cls, data: dict | str, cognite_client: CogniteClient | None = None) -> ViewResolveItem:
if isinstance(data, str):
return cls._load(json.loads(data), cognite_client=cognite_client)
elif isinstance(data, Dict):
elif isinstance(data, dict):
return cls(data, cognite_client=cognite_client)


Expand Down
12 changes: 5 additions & 7 deletions cognite/client/data_classes/three_d.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import annotations

from typing import TYPE_CHECKING, Any, Dict, cast
from typing import TYPE_CHECKING, Any, cast

from cognite.client.data_classes._base import (
CogniteLabelUpdate,
Expand Down Expand Up @@ -196,9 +196,8 @@ def __init__(
@classmethod
def _load(cls, resource: dict | str, cognite_client: CogniteClient | None = None) -> ThreeDModelRevision:
instance = super()._load(resource, cognite_client)
if isinstance(resource, Dict):
if instance.camera is not None:
instance.camera = RevisionCameraProperties(**instance.camera)
if isinstance(resource, dict) and instance.camera is not None:
instance.camera = RevisionCameraProperties(**instance.camera)
return instance


Expand Down Expand Up @@ -320,9 +319,8 @@ def __init__(
@classmethod
def _load(cls, resource: dict | str, cognite_client: CogniteClient | None = None) -> ThreeDNode:
instance = super()._load(resource, cognite_client)
if isinstance(resource, Dict):
if instance.bounding_box is not None:
instance.bounding_box = BoundingBox3D(**instance.bounding_box)
if isinstance(resource, dict) and instance.bounding_box is not None:
instance.bounding_box = BoundingBox3D(**instance.bounding_box)
return instance


Expand Down
6 changes: 3 additions & 3 deletions cognite/client/data_classes/transformations/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import logging
from abc import abstractmethod
from copy import deepcopy
from typing import TYPE_CHECKING, Any, Awaitable, Dict, Literal, cast
from typing import TYPE_CHECKING, Any, Awaitable, Literal, cast

from cognite.client.data_classes._base import (
CogniteFilter,
Expand Down Expand Up @@ -554,11 +554,11 @@ def __init__(
@classmethod
def _load(cls, resource: dict | str, cognite_client: CogniteClient | None = None) -> TransformationPreviewResult:
instance = super()._load(resource, cognite_client)
if isinstance(instance.schema, Dict):
if isinstance(instance.schema, dict):
items = instance.schema.get("items")
if items is not None:
instance.schema = TransformationSchemaColumnList._load(items, cognite_client=cognite_client)
if isinstance(instance.results, Dict):
if isinstance(instance.results, dict):
items = instance.results.get("items")
if items is not None:
instance.results = items
Expand Down
4 changes: 2 additions & 2 deletions cognite/client/data_classes/transformations/jobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import asyncio
import time
from enum import Enum
from typing import TYPE_CHECKING, Dict, cast
from typing import TYPE_CHECKING, cast

from cognite.client.data_classes._base import CogniteFilter, CogniteResource, CogniteResourceList
from cognite.client.data_classes.transformations.common import TransformationDestination, _load_destination_dct
Expand Down Expand Up @@ -253,7 +253,7 @@ async def wait_async(self, polling_interval: float = 1, timeout: float | None =
@classmethod
def _load(cls, resource: dict | str, cognite_client: CogniteClient | None = None) -> TransformationJob:
instance = super()._load(resource, cognite_client)
if isinstance(instance.destination, Dict):
if isinstance(instance.destination, dict):
instance.destination = _load_destination_dct(instance.destination)
return instance

Expand Down
4 changes: 2 additions & 2 deletions cognite/client/data_classes/transformations/schema.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import annotations

from typing import TYPE_CHECKING, Dict, cast
from typing import TYPE_CHECKING, cast

from cognite.client.data_classes._base import CogniteResource, CogniteResourceList
from cognite.client.utils._text import convert_all_keys_to_snake_case
Expand Down Expand Up @@ -63,7 +63,7 @@ def __init__(
@classmethod
def _load(cls, resource: dict | str, cognite_client: CogniteClient | None = None) -> TransformationSchemaColumn:
instance = super()._load(resource, cognite_client)
if isinstance(instance.type, Dict):
if isinstance(instance.type, dict):
snake_dict = convert_all_keys_to_snake_case(instance.type)
instance_type = instance.type.get("type")
if instance_type == "array":
Expand Down

0 comments on commit 2372eeb

Please sign in to comment.