Skip to content

Commit

Permalink
Simplify conditional expressions with True/False as output (#1418)
Browse files Browse the repository at this point in the history
Co-authored-by: Hayden Hohns <[email protected]>
Co-authored-by: Erlend vollset <[email protected]>
  • Loading branch information
3 people authored Oct 13, 2023
1 parent 4cff041 commit f5c2960
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 32 deletions.
29 changes: 12 additions & 17 deletions cognite/client/_api/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,11 +192,10 @@ def create(
sleep_time = 1.0 # seconds
for i in range(MAX_RETRIES):
file = self._cognite_client.files.retrieve(id=file_id)
if file is None or not file.uploaded:
time.sleep(sleep_time)
sleep_time *= 2
else:
if file and file.uploaded:
break
time.sleep(sleep_time)
sleep_time *= 2
else:
raise OSError("Could not retrieve file from files API")

Expand Down Expand Up @@ -436,7 +435,7 @@ def _zip_and_upload_folder(self, folder: str, name: str, external_id: str | None
for filename in files:
zf.write(Path(root, filename))

overwrite = True if external_id else False
overwrite = bool(external_id)
file = self._cognite_client.files.upload_bytes(
zip_path.read_bytes(), name=f"{name}.zip", external_id=external_id, overwrite=overwrite
)
Expand Down Expand Up @@ -465,7 +464,7 @@ def _zip_and_upload_handle(self, function_handle: Callable, name: str, external_
if docstr_requirements:
zf.write(requirements_path, arcname=REQUIREMENTS_FILE_NAME)

overwrite = True if external_id else False
overwrite = bool(external_id)
file = self._cognite_client.files.upload_bytes(
zip_path.read_bytes(), name=f"{name}.zip", external_id=external_id, overwrite=overwrite
)
Expand All @@ -476,8 +475,9 @@ def _assert_exactly_one_of_folder_or_file_id_or_function_handle(
folder: str | None, file_id: int | None, function_handle: Callable[..., Any] | None
) -> None:
source_code_options = {"folder": folder, "file_id": file_id, "function_handle": function_handle}
given_source_code_options = [key for key in source_code_options.keys() if source_code_options[key]]
if len(given_source_code_options) < 1:
# TODO: Fix to use exactly_one_is_not_none function
given_source_code_options = [key for key in source_code_options if source_code_options[key]]
if not given_source_code_options:
raise TypeError("Exactly one of the arguments folder, file_id and handle is required, but none were given.")
elif len(given_source_code_options) > 1:
raise TypeError(
Expand Down Expand Up @@ -599,7 +599,7 @@ def validate_function_folder(root_path: str, function_path: str, skip_folder_val
def _validate_function_handle(handle_obj: Callable | ast.FunctionDef) -> None:
if isinstance(handle_obj, ast.FunctionDef):
name = handle_obj.name
accepts_args = set(arg.arg for arg in handle_obj.args.args)
accepts_args = {arg.arg for arg in handle_obj.args.args}
else:
name = handle_obj.__name__
accepts_args = set(signature(handle_obj).parameters)
Expand Down Expand Up @@ -686,14 +686,9 @@ def _get_fn_docstring_requirements(fn: Callable) -> list[str]:
Returns:
list[str]: A (possibly empty) list of requirements.
"""
docstr = getdoc(fn)

if docstr:
reqs = _extract_requirements_from_doc_string(docstr)
if reqs:
parsed_reqs = _validate_and_parse_requirements(reqs)
return parsed_reqs

if docstr := getdoc(fn):
if reqs := _extract_requirements_from_doc_string(docstr):
return _validate_and_parse_requirements(reqs)
return []


Expand Down
13 changes: 3 additions & 10 deletions cognite/client/_api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ def _configure_headers(
headers["x-cdp-app"] = self._config.client_name
headers["cdf-version"] = api_subversion or self._api_subversion
if "User-Agent" in headers:
headers["User-Agent"] += " " + get_user_agent()
headers["User-Agent"] += f" {get_user_agent()}"
else:
headers["User-Agent"] = get_user_agent()
headers.update(additional_headers)
Expand Down Expand Up @@ -259,11 +259,7 @@ def _is_retryable(self, method: str, path: str) -> bool:
if method not in valid_methods:
raise ValueError(f"Method {method} is not valid. Must be one of {valid_methods}")

if method in ["GET", "PUT", "PATCH"]:
return True
if method == "POST" and self._url_is_retryable(path):
return True
return False
return method in ["GET", "PUT", "PATCH"] or method == "POST" and self._url_is_retryable(path)

@classmethod
@functools.lru_cache(64)
Expand All @@ -275,10 +271,7 @@ def _url_is_retryable(cls, url: str) -> bool:
if not match:
raise ValueError(f"URL {url} is not valid. Cannot resolve whether or not it is retryable")
path = match.group(1)
for pattern in cls._RETRYABLE_POST_ENDPOINT_REGEX_PATTERNS:
if re.match(pattern, path):
return True
return False
return any(re.match(pattern, path) for pattern in cls._RETRYABLE_POST_ENDPOINT_REGEX_PATTERNS)

def _retrieve(
self,
Expand Down
2 changes: 1 addition & 1 deletion tests/tests_integration/test_api/test_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ def test_aggregate_has_type(self, cognite_client: CogniteClient, event_list: Eve

count = cognite_client.events.aggregate_count(EventProperty.type, advanced_filter=is_integration_test)

assert count >= sum(1 for e in event_list if e.type)
assert count >= len([e for e in event_list if e.type])

def test_aggregate_type_count(self, cognite_client: CogniteClient, event_list: EventList) -> None:
f = filters
Expand Down
8 changes: 4 additions & 4 deletions tests/tests_integration/test_api/test_sequences.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,9 @@ def root_asset(cognite_client: CogniteClient) -> Asset:
name="integration_test:root_asset",
external_id="integration_test:root_asset",
)
retrieved = cognite_client.assets.retrieve_multiple(external_ids=[root_asset.external_id], ignore_unknown_ids=True)
if retrieved:
if retrieved := cognite_client.assets.retrieve_multiple(
external_ids=[root_asset.external_id], ignore_unknown_ids=True
):
return retrieved[0]
return cognite_client.assets.create(root_asset)

Expand Down Expand Up @@ -280,8 +281,7 @@ def test_aggregate_asset_id_count(self, cognite_client: CogniteClient, sequence_
count = cognite_client.sequences.aggregate_cardinality_values(
SequenceProperty.asset_id, advanced_filter=is_integration_test
)

assert count >= sum(1 for s in sequence_list if s.asset_id is not None)
assert count >= len([s for s in sequence_list if s.asset_id is not None])

def test_aggregate_metadata_keys_count(self, cognite_client: CogniteClient, sequence_list: SequenceList) -> None:
f = filters
Expand Down

0 comments on commit f5c2960

Please sign in to comment.