Skip to content

Commit

Permalink
fix: scripts/generate_code_snippets.py doesn't work with cached_pro…
Browse files Browse the repository at this point in the history
…perty (#2051)
  • Loading branch information
haakonvt authored Dec 10, 2024
1 parent b10ca2a commit 279cda9
Showing 1 changed file with 20 additions and 19 deletions.
39 changes: 20 additions & 19 deletions cognite/client/_api/units.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import difflib
from collections import defaultdict
from functools import cached_property
from functools import cache
from itertools import chain
from typing import TYPE_CHECKING, Literal, overload

Expand All @@ -21,6 +21,24 @@
from cognite.client import ClientConfig, CogniteClient


@cache
def _create_unit_lookups(unit_client: UnitAPI) -> tuple[dict[str, dict[str, Unit]], dict[str, list[Unit]]]:
units = unit_client.list()
alias_by_quantity: defaultdict[str, dict[str, Unit]] = defaultdict(dict)
for unit in units:
dct = alias_by_quantity[unit.quantity]
# fun fact, for some units, alias_names has duplicates:
for alias in unit.alias_names:
dct[alias] = unit

alias_lookup = defaultdict(list)
for dct in alias_by_quantity.values():
for alias, unit in dct.items():
alias_lookup[alias].append(unit)
# we want failed lookups to raise, so we convert to dict:
return dict(alias_by_quantity), dict(alias_lookup)


class UnitAPI(APIClient):
_RESOURCE_PATH = "/units"

Expand Down Expand Up @@ -72,23 +90,6 @@ def retrieve(
ignore_unknown_ids=ignore_unknown_ids,
)

@cached_property
def _create_unit_lookups(self) -> tuple[dict[str, dict[str, Unit]], dict[str, list[Unit]]]:
units = self.list()
alias_by_quantity: defaultdict[str, dict[str, Unit]] = defaultdict(dict)
for unit in units:
dct = alias_by_quantity[unit.quantity]
# fun fact, for some units, alias_names has duplicates:
for alias in unit.alias_names:
dct[alias] = unit

alias_lookup = defaultdict(list)
for dct in alias_by_quantity.values():
for alias, unit in dct.items():
alias_lookup[alias].append(unit)
# we want failed lookups to raise, so we convert to dict:
return dict(alias_by_quantity), dict(alias_lookup)

@overload
def from_alias(
self,
Expand Down Expand Up @@ -150,7 +151,7 @@ def from_alias(
>>> unit_matches = client.units.from_alias("kilo watt", return_closest_matches=True)
"""
alias_by_quantity, alias_lookup = self._create_unit_lookups
alias_by_quantity, alias_lookup = _create_unit_lookups(self)
if quantity is None:
return self._lookup_unit_by_alias(alias, alias_lookup, return_ambiguous, return_closest_matches)
else:
Expand Down

0 comments on commit 279cda9

Please sign in to comment.