Skip to content

Commit 7f8ee73

Browse files
authored
chore: Code quality improvements (#103)
1 parent c212fb8 commit 7f8ee73

File tree

13 files changed

+49
-63
lines changed

13 files changed

+49
-63
lines changed

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ dev = [
5353
"flake8-noqa ~= 1.3.1",
5454
"flake8-pytest-style ~= 1.7.2",
5555
"flake8-quotes ~= 3.3.2",
56+
"flake8-simplify ~= 0.20.0",
5657
"flake8-unused-arguments ~= 0.0.13",
5758
"isort ~= 5.12.0",
5859
"mypy ~= 1.3.0",

src/apify/_memory_storage/memory_storage_client.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import asyncio
2+
import contextlib
23
import os
34
from pathlib import Path
45
from typing import List, Optional
@@ -167,11 +168,8 @@ async def _handle_default_key_value_store(self, folder: str) -> None:
167168
for entity in possible_input_keys:
168169
original_file_path = os.path.join(folder, entity)
169170
temp_file_path = os.path.join(temporary_path, entity)
170-
try:
171+
with contextlib.suppress(Exception):
171172
await rename(original_file_path, temp_file_path)
172-
except Exception:
173-
# Ignore
174-
pass
175173

176174
# Remove the original folder and all its content
177175
counter = 0

src/apify/_memory_storage/resource_clients/base_resource_client.py

Lines changed: 17 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -93,24 +93,23 @@ def _find_or_create_client_by_id_or_name(
9393
storage_path = possible_storage_path
9494

9595
# If it's not found, try going through the storages dir and finding it by metadata
96-
if not storage_path:
97-
if os.access(storages_dir, os.F_OK):
98-
for entry in os.scandir(storages_dir):
99-
if not entry.is_dir():
100-
continue
101-
metadata_path = os.path.join(entry.path, '__metadata__.json')
102-
if not os.access(metadata_path, os.F_OK):
103-
continue
104-
with open(metadata_path, encoding='utf-8') as metadata_file:
105-
metadata = json.load(metadata_file)
106-
if id and id == metadata.get('id'):
107-
storage_path = entry.path
108-
name = metadata.get(name)
109-
break
110-
if name and name == metadata.get('name'):
111-
storage_path = entry.path
112-
id = metadata.get(id)
113-
break
96+
if not storage_path and os.access(storages_dir, os.F_OK):
97+
for entry in os.scandir(storages_dir):
98+
if not entry.is_dir():
99+
continue
100+
metadata_path = os.path.join(entry.path, '__metadata__.json')
101+
if not os.access(metadata_path, os.F_OK):
102+
continue
103+
with open(metadata_path, encoding='utf-8') as metadata_file:
104+
metadata = json.load(metadata_file)
105+
if id and id == metadata.get('id'):
106+
storage_path = entry.path
107+
name = metadata.get(name)
108+
break
109+
if name and name == metadata.get('name'):
110+
storage_path = entry.path
111+
id = metadata.get(id)
112+
break
114113

115114
# As a last resort, try to check if the accessed storage is the default one,
116115
# and the folder has no metadata

src/apify/_memory_storage/resource_clients/key_value_store.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -313,9 +313,8 @@ async def set_record(self, key: str, value: Any, content_type: Optional[str] = N
313313
existing_store_by_id._records[key] = record
314314

315315
if self._memory_storage_client._persist_storage:
316-
if old_record is not None:
317-
if _filename_from_record(old_record) != _filename_from_record(record):
318-
await existing_store_by_id._delete_persisted_record(old_record)
316+
if old_record is not None and _filename_from_record(old_record) != _filename_from_record(record):
317+
await existing_store_by_id._delete_persisted_record(old_record)
319318

320319
await existing_store_by_id._persist_record(record)
321320

src/apify/_utils.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -180,10 +180,8 @@ def _get_memory_usage_bytes() -> int:
180180
current_process = psutil.Process(os.getpid())
181181
mem = int(current_process.memory_info().rss or 0)
182182
for child in current_process.children(recursive=True):
183-
try:
183+
with contextlib.suppress(psutil.NoSuchProcess):
184184
mem += int(child.memory_info().rss or 0)
185-
except psutil.NoSuchProcess:
186-
pass
187185
return mem
188186

189187

src/apify/actor.py

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import asyncio
2+
import contextlib
23
import inspect
34
import logging
45
import os
@@ -271,28 +272,22 @@ async def _respond_to_migrating_event(self, _event_data: Any) -> None:
271272
# Don't emit any more regular persist state events
272273
if self._send_persist_state_interval_task and not self._send_persist_state_interval_task.cancelled():
273274
self._send_persist_state_interval_task.cancel()
274-
try:
275+
with contextlib.suppress(asyncio.CancelledError):
275276
await self._send_persist_state_interval_task
276-
except asyncio.CancelledError:
277-
pass
278277

279278
self._event_manager.emit(ActorEventTypes.PERSIST_STATE, {'isMigrating': True})
280279
self._was_final_persist_state_emitted = True
281280

282281
async def _cancel_event_emitting_intervals(self) -> None:
283282
if self._send_persist_state_interval_task and not self._send_persist_state_interval_task.cancelled():
284283
self._send_persist_state_interval_task.cancel()
285-
try:
284+
with contextlib.suppress(asyncio.CancelledError):
286285
await self._send_persist_state_interval_task
287-
except asyncio.CancelledError:
288-
pass
289286

290287
if self._send_system_info_interval_task and not self._send_system_info_interval_task.cancelled():
291288
self._send_system_info_interval_task.cancel()
292-
try:
289+
with contextlib.suppress(asyncio.CancelledError):
293290
await self._send_system_info_interval_task
294-
except asyncio.CancelledError:
295-
pass
296291

297292
@classmethod
298293
async def exit(
@@ -1299,8 +1294,8 @@ async def _create_proxy_configuration_internal(
12991294

13001295
if actor_proxy_input is not None:
13011296
if actor_proxy_input.get('useApifyProxy', False):
1302-
country_code = country_code or actor_proxy_input.get('apifyProxyCountry', None)
1303-
groups = groups or actor_proxy_input.get('apifyProxyGroups', None)
1297+
country_code = country_code or actor_proxy_input.get('apifyProxyCountry')
1298+
groups = groups or actor_proxy_input.get('apifyProxyGroups')
13041299
else:
13051300
proxy_urls = actor_proxy_input.get('proxyUrls', [])
13061301
if not proxy_urls:

src/apify/event_manager.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import asyncio
2+
import contextlib
23
import inspect
34
import json
45
from collections import defaultdict
@@ -200,10 +201,8 @@ async def _wait_for_listeners() -> None:
200201
logger.warning('Timed out waiting for event listeners to complete, unfinished event listeners will be canceled')
201202
for pending_task in pending:
202203
pending_task.cancel()
203-
try:
204+
with contextlib.suppress(asyncio.CancelledError):
204205
await pending_task
205-
except asyncio.CancelledError:
206-
pass
207206
else:
208207
await _wait_for_listeners()
209208

src/apify/storages/base_storage.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -131,9 +131,8 @@ async def open(
131131
return cast(Self, cached_storage)
132132

133133
# Purge default storages if configured
134-
if used_config.purge_on_start:
135-
if isinstance(used_client, MemoryStorageClient):
136-
await used_client._purge_on_start()
134+
if used_config.purge_on_start and isinstance(used_client, MemoryStorageClient):
135+
await used_client._purge_on_start()
137136

138137
assert cls._storage_creating_lock is not None
139138
async with cls._storage_creating_lock:

tests/unit/actor/test_actor_lifecycle.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import asyncio
2+
import contextlib
23
from datetime import datetime
34
from typing import Any, Callable
45
from unittest.mock import AsyncMock
@@ -86,12 +87,10 @@ async def test_with_actor_fail(self) -> None:
8687
assert my_actor._is_initialized is False
8788

8889
async def test_with_actor_failed(self) -> None:
89-
try:
90+
with contextlib.suppress(Exception):
9091
async with Actor() as my_actor:
9192
assert my_actor._is_initialized
9293
raise Exception('Failed')
93-
except Exception:
94-
pass
9594
assert my_actor._is_initialized is False
9695

9796
async def test_raise_on_fail_without_init(self) -> None:

tests/unit/actor/test_actor_log.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import contextlib
12
import logging
23
import sys
34

@@ -11,7 +12,7 @@
1112
class TestActorLog:
1213
async def test_actor_log(self, caplog: pytest.LogCaptureFixture) -> None:
1314
caplog.set_level(logging.DEBUG, logger='apify')
14-
try:
15+
with contextlib.suppress(RuntimeError):
1516
async with Actor:
1617
# Test Actor.log
1718
Actor.log.debug('Debug message')
@@ -32,8 +33,6 @@ async def test_actor_log(self, caplog: pytest.LogCaptureFixture) -> None:
3233

3334
# Test that exception in Actor.main is logged with the traceback
3435
raise RuntimeError('Dummy RuntimeError')
35-
except RuntimeError:
36-
pass
3736

3837
assert len(caplog.records) == 12
3938

0 commit comments

Comments
 (0)