Skip to content

Commit eda4ff6

Browse files
committed
style: formatted everything with Black
1 parent 0444be3 commit eda4ff6

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+948
-429
lines changed

aw_core/__about__.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,14 @@
22
# https://github.com/pypa/pipfile/blob/master/pipfile/__about__.py
33

44
__all__ = [
5-
"__title__", "__summary__", "__uri__", "__version__", "__author__",
6-
"__email__", "__license__", "__copyright__",
5+
"__title__",
6+
"__summary__",
7+
"__uri__",
8+
"__version__",
9+
"__author__",
10+
"__email__",
11+
"__license__",
12+
"__copyright__",
713
]
814

915
__title__ = "aw-core"

aw_core/config.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ def load_config(appname, default_config):
1919

2020
# Override defaults from existing config file
2121
if os.path.isfile(config_file_path):
22-
with open(config_file_path, 'r') as f:
22+
with open(config_file_path, "r") as f:
2323
config.read_file(f)
2424

2525
# Overwrite current config file (necessary in case new default would be added)
@@ -31,5 +31,5 @@ def load_config(appname, default_config):
3131
def save_config(appname, config):
3232
config_dir = dirs.get_config_dir(appname)
3333
config_file_path = os.path.join(config_dir, "{}.ini".format(appname))
34-
with open(config_file_path, 'w') as f:
34+
with open(config_file_path, "w") as f:
3535
config.write(f)

aw_core/decorators.py

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,15 @@ def g(*args, **kwargs):
2020
# TODO: Use logging module instead?
2121
nonlocal warned_for
2222
if not warned_for:
23-
warnings.simplefilter('always', DeprecationWarning) # turn off filter
24-
warnings.warn("Call to deprecated function {}, this warning will only show once per function.".format(f.__name__), category=DeprecationWarning, stacklevel=2)
25-
warnings.simplefilter('default', DeprecationWarning) # reset filter
23+
warnings.simplefilter("always", DeprecationWarning) # turn off filter
24+
warnings.warn(
25+
"Call to deprecated function {}, this warning will only show once per function.".format(
26+
f.__name__
27+
),
28+
category=DeprecationWarning,
29+
stacklevel=2,
30+
)
31+
warnings.simplefilter("default", DeprecationWarning) # reset filter
2632
warned_for = True
2733
return f(*args, **kwargs)
2834

@@ -37,7 +43,12 @@ def g(*args, **kwargs):
3743
f(*args, **kwargs)
3844
except exception as e:
3945
# TODO: Use warnings module instead?
40-
logging.error("{} crashed due to exception, restarting.".format(f.__name__))
46+
logging.error(
47+
"{} crashed due to exception, restarting.".format(f.__name__)
48+
)
4149
logging.error(e)
42-
time.sleep(delay) # To prevent extremely fast restarts in case of bad state.
50+
time.sleep(
51+
delay
52+
) # To prevent extremely fast restarts in case of bad state.
53+
4354
return g

aw_core/dirs.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ def wrapper(subpath: Optional[str]) -> str:
1818
path = f(subpath)
1919
ensure_path_exists(path)
2020
return path
21+
2122
return wrapper
2223

2324

aw_core/log.py

Lines changed: 36 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -20,23 +20,36 @@ def get_log_file_path() -> Optional[str]: # pragma: no cover
2020
return log_file_path
2121

2222

23-
def setup_logging(name: str, testing=False, verbose=False,
24-
log_stderr=True, log_file=False, log_file_json=False): # pragma: no cover
23+
def setup_logging(
24+
name: str,
25+
testing=False,
26+
verbose=False,
27+
log_stderr=True,
28+
log_file=False,
29+
log_file_json=False,
30+
): # pragma: no cover
2531
root_logger = logging.getLogger()
2632
root_logger.setLevel(logging.DEBUG if verbose else logging.INFO)
2733
root_logger.handlers = []
2834

2935
if log_stderr:
3036
root_logger.addHandler(_create_stderr_handler())
3137
if log_file:
32-
root_logger.addHandler(_create_file_handler(name, testing=testing, log_json=log_file_json))
38+
root_logger.addHandler(
39+
_create_file_handler(name, testing=testing, log_json=log_file_json)
40+
)
3341

3442

3543
def _get_latest_log_files(name, testing=False) -> List[str]: # pragma: no cover
3644
"""Returns a list with the paths of all available logfiles for `name` sorted by latest first."""
3745
log_dir = dirs.get_log_dir(name)
3846
files = filter(lambda filename: name in filename, os.listdir(log_dir))
39-
files = filter(lambda filename: "testing" in filename if testing else "testing" not in filename, files)
47+
files = filter(
48+
lambda filename: "testing" in filename
49+
if testing
50+
else "testing" not in filename,
51+
files,
52+
)
4053
return [os.path.join(log_dir, filename) for filename in sorted(files, reverse=True)]
4154

4255

@@ -54,7 +67,9 @@ def _create_stderr_handler() -> logging.Handler: # pragma: no cover
5467
return stderr_handler
5568

5669

57-
def _create_file_handler(name, testing=False, log_json=False) -> logging.Handler: # pragma: no cover
70+
def _create_file_handler(
71+
name, testing=False, log_json=False
72+
) -> logging.Handler: # pragma: no cover
5873
log_dir = dirs.get_log_dir(name)
5974

6075
# Set logfile path and name
@@ -67,7 +82,7 @@ def _create_file_handler(name, testing=False, log_json=False) -> logging.Handler
6782
log_name = name + "_" + ("testing_" if testing else "") + now_str + file_ext
6883
log_file_path = os.path.join(log_dir, log_name)
6984

70-
fh = logging.FileHandler(log_file_path, mode='w')
85+
fh = logging.FileHandler(log_file_path, mode="w")
7186
if log_json:
7287
fh.setFormatter(_create_json_formatter())
7388
else:
@@ -77,23 +92,26 @@ def _create_file_handler(name, testing=False, log_json=False) -> logging.Handler
7792

7893

7994
def _create_human_formatter() -> logging.Formatter: # pragma: no cover
80-
return logging.Formatter('%(asctime)s [%(levelname)-5s]: %(message)s (%(name)s:%(lineno)s)', '%Y-%m-%d %H:%M:%S')
95+
return logging.Formatter(
96+
"%(asctime)s [%(levelname)-5s]: %(message)s (%(name)s:%(lineno)s)",
97+
"%Y-%m-%d %H:%M:%S",
98+
)
8199

82100

83101
def _create_json_formatter() -> logging.Formatter: # pragma: no cover
84102
supported_keys = [
85-
'asctime',
103+
"asctime",
86104
# 'created',
87-
'filename',
88-
'funcName',
89-
'levelname',
105+
"filename",
106+
"funcName",
107+
"levelname",
90108
# 'levelno',
91-
'lineno',
92-
'module',
109+
"lineno",
110+
"module",
93111
# 'msecs',
94-
'message',
95-
'name',
96-
'pathname',
112+
"message",
113+
"name",
114+
"pathname",
97115
# 'process',
98116
# 'processName',
99117
# 'relativeCreated',
@@ -103,8 +121,8 @@ def _create_json_formatter() -> logging.Formatter: # pragma: no cover
103121

104122
def log_format(x):
105123
"""Used to give JsonFormatter proper parameter format"""
106-
return ['%({0:s})'.format(i) for i in x]
124+
return ["%({0:s})".format(i) for i in x]
107125

108-
custom_format = ' '.join(log_format(supported_keys))
126+
custom_format = " ".join(log_format(supported_keys))
109127

110128
return jsonlogger.JsonFormatter(custom_format)

aw_core/models.py

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -40,11 +40,18 @@ class Event(dict):
4040
Used to represents an event.
4141
"""
4242

43-
def __init__(self, id: Id = None, timestamp: ConvertableTimestamp = None,
44-
duration: Duration = 0, data: Data = dict()) -> None:
43+
def __init__(
44+
self,
45+
id: Id = None,
46+
timestamp: ConvertableTimestamp = None,
47+
duration: Duration = 0,
48+
data: Data = dict(),
49+
) -> None:
4550
self.id = id
4651
if timestamp is None:
47-
logger.warning("Event initializer did not receive a timestamp argument, using now as timestamp")
52+
logger.warning(
53+
"Event initializer did not receive a timestamp argument, using now as timestamp"
54+
)
4855
# FIXME: The typing.cast here was required for mypy to shut up, weird...
4956
self.timestamp = datetime.now(typing.cast(timezone, timezone.utc))
5057
else:
@@ -55,17 +62,27 @@ def __init__(self, id: Id = None, timestamp: ConvertableTimestamp = None,
5562

5663
def __eq__(self, other: object) -> bool:
5764
if isinstance(other, Event):
58-
return self.timestamp == other.timestamp \
59-
and self.duration == other.duration \
65+
return (
66+
self.timestamp == other.timestamp
67+
and self.duration == other.duration
6068
and self.data == other.data
69+
)
6170
else:
62-
raise TypeError("operator not supported between instances of '{}' and '{}'".format(type(self), type(other)))
71+
raise TypeError(
72+
"operator not supported between instances of '{}' and '{}'".format(
73+
type(self), type(other)
74+
)
75+
)
6376

6477
def __lt__(self, other: object) -> bool:
6578
if isinstance(other, Event):
6679
return self.timestamp < other.timestamp
6780
else:
68-
raise TypeError("operator not supported between instances of '{}' and '{}'".format(type(self), type(other)))
81+
raise TypeError(
82+
"operator not supported between instances of '{}' and '{}'".format(
83+
type(self), type(other)
84+
)
85+
)
6986

7087
def to_json_dict(self) -> dict:
7188
"""Useful when sending data over the wire.
@@ -119,4 +136,6 @@ def duration(self, duration: Duration) -> None:
119136
elif isinstance(duration, numbers.Real):
120137
self["duration"] = timedelta(seconds=duration) # type: ignore
121138
else:
122-
raise TypeError("Couldn't parse duration of invalid type {}".format(type(duration)))
139+
raise TypeError(
140+
"Couldn't parse duration of invalid type {}".format(type(duration))
141+
)

aw_core/timeperiod.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,11 @@ def duration(self) -> timedelta:
1818

1919
def overlaps(self, other: "TimePeriod") -> bool:
2020
"""Checks if this timeperiod is overlapping partially or entirely with another timeperiod"""
21-
return self.start <= other.start < self.end \
22-
or self.start < other.end <= self.end \
21+
return (
22+
self.start <= other.start < self.end
23+
or self.start < other.end <= self.end
2324
or self in other
25+
)
2426

2527
def intersects(self, other: "TimePeriod") -> bool:
2628
"""Alias for overlaps"""
@@ -49,7 +51,11 @@ def __lt__(self, other: object) -> bool:
4951
if isinstance(other, TimePeriod):
5052
return self.start < other.start
5153
else:
52-
raise TypeError("operator not supported between instaces of '{}' and '{}'".format(type(self), type(other)))
54+
raise TypeError(
55+
"operator not supported between instaces of '{}' and '{}'".format(
56+
type(self), type(other)
57+
)
58+
)
5359

5460
def intersection(self, other: "TimePeriod") -> Optional["TimePeriod"]:
5561
"""Returns the timeperiod contained in both periods"""

aw_core/util.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,16 @@ class VersionException(Exception):
1010

1111

1212
def _version_info_tuple() -> Tuple[int, int, int]: # pragma: no cover
13-
return (sys.version_info.major,
14-
sys.version_info.minor,
15-
sys.version_info.micro)
13+
return (sys.version_info.major, sys.version_info.minor, sys.version_info.micro)
1614

1715

1816
def assert_version(required_version: Tuple[int, ...] = (3, 5)): # pragma: no cover
1917
actual_version = _version_info_tuple()
2018
if actual_version <= required_version:
21-
raise VersionException(("Python version {} not supported, you need to upgrade your Python" +
22-
" version to at least {}.").format(required_version))
19+
raise VersionException(
20+
(
21+
"Python version {} not supported, you need to upgrade your Python"
22+
+ " version to at least {}."
23+
).format(required_version)
24+
)
2325
logger.debug("Python version: {}".format(_version_info_tuple()))

aw_datastore/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
# like ellipsises. See here: https://github.com/python/typing/issues/259
1111
def get_storage_methods() -> Dict[str, Callable[[Any], storages.AbstractStorage]]:
1212
from .storages import MemoryStorage, MongoDBStorage, PeeweeStorage, SqliteStorage
13+
1314
methods: Dict[str, Callable[[Any], storages.AbstractStorage]] = {
1415
PeeweeStorage.sid: PeeweeStorage,
1516
MemoryStorage.sid: MemoryStorage,
@@ -20,6 +21,7 @@ def get_storage_methods() -> Dict[str, Callable[[Any], storages.AbstractStorage]
2021
if _platform.system() == "Linux": # pragma: no branch
2122
try:
2223
import pymongo
24+
2325
methods[MongoDBStorage.sid] = MongoDBStorage
2426
except ImportError: # pragma: no cover
2527
pass

aw_datastore/benchmark.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@ def create_test_events(n):
1717

1818
events = []
1919
for i in range(n):
20-
events.append(Event(timestamp=now + i * timedelta(seconds=1), data={"label": "asd"}))
20+
events.append(
21+
Event(timestamp=now + i * timedelta(seconds=1), data={"label": "asd"})
22+
)
2123

2224
return events
2325

@@ -49,14 +51,14 @@ def benchmark(storage: Callable[..., AbstractStorage]):
4951

5052
num_single_events = 50
5153
num_replace_events = 50
52-
num_bulk_events = 2 * 10**3
54+
num_bulk_events = 2 * 10 ** 3
5355
num_events = num_single_events + num_replace_events + num_bulk_events + 1
5456
num_final_events = num_single_events + num_bulk_events + 1
5557

5658
events = create_test_events(num_events)
5759
single_events = events[:num_single_events]
58-
replace_events = events[num_single_events:num_single_events+num_replace_events]
59-
bulk_events = events[num_single_events+num_replace_events:-1]
60+
replace_events = events[num_single_events : num_single_events + num_replace_events]
61+
bulk_events = events[num_single_events + num_replace_events : -1]
6062

6163
print(storage.__name__)
6264

0 commit comments

Comments
 (0)