Skip to content

Commit 085d823

Browse files
committed
fix: fixed warnings/nits reported by ruff
1 parent b6362bb commit 085d823

18 files changed

+163
-127
lines changed

aw_core/decorators.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
import warnings
21
import functools
32
import logging
43
import time
4+
import warnings
55

66

77
def deprecated(f): # pragma: no cover
@@ -22,9 +22,8 @@ def g(*args, **kwargs):
2222
if not warned_for:
2323
warnings.simplefilter("always", DeprecationWarning) # turn off filter
2424
warnings.warn(
25-
"Call to deprecated function {}, this warning will only show once per function.".format(
26-
f.__name__
27-
),
25+
"Call to deprecated function {}, "
26+
"this warning will only show once per function.".format(f.__name__),
2827
category=DeprecationWarning,
2928
stacklevel=2,
3029
)

aw_core/log.py

+8-3
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
from . import dirs
99
from .decorators import deprecated
1010

11-
# NOTE: Will be removed in a future version since it's not compatible with running a multi-service process
11+
# NOTE: Will be removed in a future version since it's not compatible
12+
# with running a multi-service process.
1213
# TODO: prefix with `_`
1314
log_file_path = None
1415

@@ -50,15 +51,19 @@ def setup_logging(
5051

5152
def excepthook(type_, value, traceback):
5253
root_logger.exception("Unhandled exception", exc_info=(type_, value, traceback))
53-
# call the default excepthook if log_stderr isn't true (otherwise it'll just get duplicated)
54+
# call the default excepthook if log_stderr isn't true
55+
# (otherwise it'll just get duplicated)
5456
if not log_stderr:
5557
sys.__excepthook__(type_, value, traceback)
5658

5759
sys.excepthook = excepthook
5860

5961

6062
def _get_latest_log_files(name, testing=False) -> List[str]: # pragma: no cover
61-
"""Returns a list with the paths of all available logfiles for `name` sorted by latest first."""
63+
"""
64+
Returns a list with the paths of all available logfiles for `name`,
65+
sorted by latest first.
66+
"""
6267
log_dir = dirs.get_log_dir(name)
6368
files = filter(lambda filename: name in filename, os.listdir(log_dir))
6469
files = filter(

aw_core/models.py

+10-3
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,12 @@
33
import numbers
44
import typing
55
from datetime import datetime, timedelta, timezone
6-
from typing import Any, List, Dict, Union, Optional
6+
from typing import (
7+
Any,
8+
Dict,
9+
Optional,
10+
Union,
11+
)
712

813
import iso8601
914

@@ -50,12 +55,14 @@ def __init__(
5055
self.id = id
5156
if timestamp is None:
5257
logger.warning(
53-
"Event initializer did not receive a timestamp argument, using now as timestamp"
58+
"Event initializer did not receive a timestamp argument, "
59+
"using now as timestamp"
5460
)
5561
# FIXME: The typing.cast here was required for mypy to shut up, weird...
5662
self.timestamp = datetime.now(typing.cast(timezone, timezone.utc))
5763
else:
58-
# The conversion needs to be explicit here for mypy to pick it up (lacks support for properties)
64+
# The conversion needs to be explicit here for mypy to pick it up
65+
# (lacks support for properties)
5966
self.timestamp = _timestamp_parse(timestamp)
6067
self.duration = duration # type: ignore
6168
self.data = data

aw_datastore/__init__.py

+15-9
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,20 @@
1-
from typing import Dict, Callable, Any
21
import platform as _platform
3-
4-
from .migration import check_for_migration
2+
from typing import Callable, Dict
53

64
from . import storages
75
from .datastore import Datastore
6+
from .migration import check_for_migration
87

9-
# The Callable[[Any], ...] here should be Callable[..., ...] but Python 3.5.2 doesn't
10-
# like ellipsis. See here: https://github.com/python/typing/issues/259
11-
def get_storage_methods() -> Dict[str, Callable[[Any], storages.AbstractStorage]]:
12-
from .storages import MemoryStorage, MongoDBStorage, PeeweeStorage, SqliteStorage
138

14-
methods: Dict[str, Callable[[Any], storages.AbstractStorage]] = {
9+
def get_storage_methods() -> Dict[str, Callable[..., storages.AbstractStorage]]:
10+
from .storages import (
11+
MemoryStorage,
12+
MongoDBStorage,
13+
PeeweeStorage,
14+
SqliteStorage,
15+
)
16+
17+
methods: Dict[str, Callable[..., storages.AbstractStorage]] = {
1518
PeeweeStorage.sid: PeeweeStorage,
1619
MemoryStorage.sid: MemoryStorage,
1720
SqliteStorage.sid: SqliteStorage,
@@ -20,10 +23,13 @@ def get_storage_methods() -> Dict[str, Callable[[Any], storages.AbstractStorage]
2023
# MongoDB is not supported on Windows or macOS
2124
if _platform.system() == "Linux": # pragma: no branch
2225
try:
23-
import pymongo
26+
import pymongo # noqa: F401
2427

2528
methods[MongoDBStorage.sid] = MongoDBStorage
2629
except ImportError: # pragma: no cover
2730
pass
2831

2932
return methods
33+
34+
35+
__all__ = ["Datastore", "get_storage_methods", "check_for_migration"]

aw_datastore/datastore.py

+22-14
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
import logging
2-
from datetime import datetime, timezone, timedelta
3-
from typing import Dict, List, Union, Callable, Optional
2+
from datetime import datetime, timedelta, timezone
3+
from typing import (
4+
Callable,
5+
Dict,
6+
List,
7+
Optional,
8+
Union,
9+
)
410

511
from aw_core.models import Event
612

@@ -122,14 +128,16 @@ def insert(self, events: Union[Event, List[Event]]) -> Optional[Event]:
122128
If a single event is inserted, return the event with its id assigned.
123129
If several events are inserted, returns None. (This is due to there being no efficient way of getting ids out when doing bulk inserts with some datastores such as peewee/SQLite)
124130
"""
131+
125132
# NOTE: Should we keep the timestamp checking?
133+
warn_older_event = False
134+
126135
# Get last event for timestamp check after insert
127-
"""
128-
last_event_list = self.get(1)
129-
last_event = None
130-
if last_event_list:
131-
last_event = last_event_list[0]
132-
"""
136+
if warn_older_event:
137+
last_event_list = self.get(1)
138+
last_event = None
139+
if last_event_list:
140+
last_event = last_event_list[0]
133141

134142
now = datetime.now(tz=timezone.utc)
135143

@@ -163,13 +171,13 @@ def insert(self, events: Union[Event, List[Event]]) -> Optional[Event]:
163171
raise TypeError
164172

165173
# Warn if timestamp is older than last event
166-
"""
167-
if last_event and oldest_event:
174+
if warn_older_event and last_event and oldest_event:
168175
if oldest_event.timestamp < last_event.timestamp: # pragma: no cover
169-
self.logger.warning("Inserting event that has a older timestamp than previous event!" +
170-
"\nPrevious:" + str(last_event) +
171-
"\nInserted:" + str(oldest_event))
172-
"""
176+
self.logger.warning(
177+
f"""Inserting event that has a older timestamp than previous event!
178+
Previous: {last_event}
179+
Inserted: {oldest_event}"""
180+
)
173181

174182
return inserted
175183

aw_datastore/migration.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
from typing import Optional, List
2-
import os
3-
import re
41
import logging
2+
import os
3+
from typing import List, Optional
54

65
from aw_core.dirs import get_data_dir
6+
77
from .storages import AbstractStorage
88

99
logger = logging.getLogger(__name__)

aw_datastore/storages/__init__.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,15 @@
33
logger: _logging.Logger = _logging.getLogger(__name__)
44

55
from .abstract import AbstractStorage
6-
76
from .memory import MemoryStorage
87
from .mongodb import MongoDBStorage
98
from .peewee import PeeweeStorage
109
from .sqlite import SqliteStorage
10+
11+
__all__ = [
12+
"AbstractStorage",
13+
"MemoryStorage",
14+
"MongoDBStorage",
15+
"PeeweeStorage",
16+
"SqliteStorage",
17+
]

aw_datastore/storages/abstract.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
1-
import logging
2-
from typing import List, Dict, Optional
1+
from abc import ABCMeta, abstractmethod
32
from datetime import datetime
4-
from abc import ABCMeta, abstractmethod, abstractproperty
3+
from typing import Dict, List, Optional
54

65
from aw_core.models import Event
76

aw_datastore/storages/mongodb.py

-3
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
1-
import logging
21
from typing import List, Dict, Optional
32
from datetime import datetime, timezone
43

5-
import iso8601
6-
74
# will be unavailable if pymongo is
85
try:
96
from bson.objectid import ObjectId

aw_query/__init__.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
from . import exceptions
2-
from . import query2
3-
41
from .query2 import query
2+
3+
__all__ = ["query"]

aw_query/functions.py

-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import re
21
import iso8601
32
from typing import Optional, Callable, Dict, Any, List
43
from inspect import signature

aw_query/query2.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -290,19 +290,19 @@ def interpret(self, datastore: Datastore, namespace: dict):
290290
@staticmethod
291291
def parse(string: str, namespace: dict) -> QToken:
292292
entries_str = string[1:-1]
293-
l: List[QToken] = []
293+
ls: List[QToken] = []
294294
while len(entries_str) > 0:
295295
entries_str = entries_str.strip()
296-
if len(l) > 0 and entries_str[0] == ",":
296+
if len(ls) > 0 and entries_str[0] == ",":
297297
entries_str = entries_str[1:]
298298
# parse
299299
(val_t, val_str), entries_str = _parse_token(entries_str, namespace)
300300
if not val_t:
301301
raise QueryParseException("List expected a value, got nothing")
302302
val = val_t.parse(val_str, namespace)
303303
# set
304-
l.append(val)
305-
return QList(l)
304+
ls.append(val)
305+
return QList(ls)
306306

307307
@staticmethod
308308
def check(string: str):

aw_transform/chunk_events_by_key.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import logging
2-
from typing import List, Dict
32
from datetime import timedelta
3+
from typing import List
44

55
from aw_core.models import Event
66

tests/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
from . import context
1+
from . import context # noqa: F401

tests/test_config.py

+12-7
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
11
import shutil
22
from configparser import ConfigParser
3+
from pathlib import Path
34

4-
import pytest
55
import deprecation
6-
6+
import pytest
77
from aw_core import dirs
8-
from aw_core.config import load_config, save_config, load_config_toml, save_config_toml
8+
from aw_core.config import (
9+
load_config,
10+
load_config_toml,
11+
save_config,
12+
save_config_toml,
13+
)
914

1015
appname = "aw-core-test"
1116
section = "section"
@@ -34,8 +39,8 @@ def clean_config():
3439

3540
def test_create():
3641
appname = "aw-core-test"
37-
section = "section"
3842
config_dir = dirs.get_config_dir(appname)
43+
assert Path(config_dir).exists()
3944

4045

4146
def test_config_defaults():
@@ -61,9 +66,9 @@ def test_config_no_defaults():
6166

6267
def test_config_override():
6368
# Create a minimal config file with one overridden value
64-
config = """[section]
69+
config_str = """[section]
6570
somevalue = 1000.1"""
66-
save_config_toml(appname, config)
71+
save_config_toml(appname, config_str)
6772

6873
# Open non-default config file and verify that values are correct
6974
config = load_config_toml(appname, default_config_str)
@@ -74,7 +79,7 @@ def test_config_override():
7479
def test_config_ini():
7580
# Create default config
7681
default_config = ConfigParser()
77-
default_config[section] = {"somestring": "Hello World!", "somevalue": 12.3}
82+
default_config[section] = {"somestring": "Hello World!", "somevalue": 12.3} # type: ignore
7883

7984
# Load non-existing config (will create a default config file)
8085
config = load_config(appname, default_config)

tests/test_datastore.py

+2-6
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,15 @@
11
import logging
22
import random
3-
import iso8601
43
from datetime import datetime, timedelta, timezone
5-
import iso8601
64

5+
import iso8601
76
import pytest
8-
9-
from . import context
10-
117
from aw_core.models import Event
128
from aw_datastore import get_storage_methods
139

10+
from . import context # noqa: F401
1411
from .utils import param_datastore_objects, param_testing_buckets_cm
1512

16-
1713
logging.basicConfig(level=logging.DEBUG)
1814

1915
# Useful when you just want some placeholder time in your events, saves typing

tests/test_heartbeat.py

+1-5
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,8 @@
1-
from datetime import datetime, timedelta, timezone
2-
import json
3-
import logging
1+
from datetime import datetime, timedelta
42

53
from aw_core.models import Event
64
from aw_transform import heartbeat_merge, heartbeat_reduce
75

8-
import unittest
9-
106

117
def test_heartbeat_merge():
128
"""Events should merge"""

0 commit comments

Comments
 (0)