Skip to content
This repository was archived by the owner on Apr 4, 2024. It is now read-only.

Commit 8c2ed54

Browse files
authored
Use ruff format correctly. (#22)
2 parents 757e0fe + 255e5fd commit 8c2ed54

File tree

7 files changed

+94
-50
lines changed

7 files changed

+94
-50
lines changed

.github/workflows/python-ci.yml

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ on:
33
branches: [main]
44
pull_request:
55
paths:
6-
- 'python/**'
6+
- "python/**"
77
defaults:
88
run:
99
working-directory: python/selfie-lib
@@ -24,9 +24,9 @@ jobs:
2424
- name: Set up Python
2525
uses: actions/setup-python@v5
2626
with:
27-
python-version-file: 'python/selfie-lib/pyproject.toml'
28-
cache: 'poetry'
27+
python-version-file: "python/selfie-lib/pyproject.toml"
28+
cache: "poetry"
2929
- run: poetry install
3030
- run: poetry run pytest -vv
3131
- run: poetry run pyright
32-
- run: poetry run ruff check
32+
- run: poetry run ruff format --check

python/selfie-lib/selfie_lib/ArrayMap.py

Lines changed: 23 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,42 +2,46 @@
22
from typing import List, TypeVar, Union
33
from abc import abstractmethod, ABC
44

5-
T = TypeVar('T')
6-
V = TypeVar('V')
7-
K = TypeVar('K')
5+
T = TypeVar("T")
6+
V = TypeVar("V")
7+
K = TypeVar("K")
8+
89

910
class ListBackedSet(Set[T], ABC):
1011
@abstractmethod
11-
def __len__(self) -> int: ...
12+
def __len__(self) -> int:
13+
...
1214

1315
@abstractmethod
14-
def __getitem__(self, index: Union[int, slice]) -> Union[T, List[T]]: ...
16+
def __getitem__(self, index: Union[int, slice]) -> Union[T, List[T]]:
17+
...
1518

1619
def __contains__(self, item: object) -> bool:
1720
for i in range(len(self)):
1821
if self[i] == item:
1922
return True
2023
return False
2124

25+
2226
class ArraySet(ListBackedSet[K]):
2327
__data: List[K]
2428

2529
def __init__(self, data: List[K]):
2630
raise NotImplementedError("Use ArraySet.empty() instead")
2731

2832
@classmethod
29-
def __create(cls, data: List[K]) -> 'ArraySet[K]':
33+
def __create(cls, data: List[K]) -> "ArraySet[K]":
3034
# Create a new instance without calling __init__
3135
instance = super().__new__(cls)
3236
instance.__data = data
3337
return instance
34-
38+
3539
def __iter__(self) -> Iterator[K]:
3640
return iter(self.__data)
3741

3842
@classmethod
39-
def empty(cls) -> 'ArraySet[K]':
40-
if not hasattr(cls, '__EMPTY'):
43+
def empty(cls) -> "ArraySet[K]":
44+
if not hasattr(cls, "__EMPTY"):
4145
cls.__EMPTY = cls([])
4246
return cls.__EMPTY
4347

@@ -52,14 +56,14 @@ def __getitem__(self, index: Union[int, slice]) -> Union[K, List[K]]:
5256
else:
5357
raise TypeError("Invalid argument type.")
5458

55-
def plusOrThis(self, element: K) -> 'ArraySet[K]':
59+
def plusOrThis(self, element: K) -> "ArraySet[K]":
5660
# TODO: use binary search, and also special sort order for strings
5761
if element in self.__data:
5862
return self
5963
else:
6064
new_data = self.__data[:]
6165
new_data.append(element)
62-
new_data.sort() # type: ignore[reportOperatorIssue]
66+
new_data.sort() # type: ignore[reportOperatorIssue]
6367
return ArraySet.__create(new_data)
6468

6569

@@ -69,8 +73,8 @@ def __init__(self, data: list):
6973
self.__data = data
7074

7175
@classmethod
72-
def empty(cls) -> 'ArrayMap[K, V]':
73-
if not hasattr(cls, '__EMPTY'):
76+
def empty(cls) -> "ArrayMap[K, V]":
77+
if not hasattr(cls, "__EMPTY"):
7478
cls.__EMPTY = cls([])
7579
return cls.__EMPTY
7680

@@ -86,7 +90,7 @@ def __iter__(self) -> Iterator[K]:
8690
def __len__(self) -> int:
8791
return len(self.__data) // 2
8892

89-
def __binary_search_key(self, key: K) -> int:
93+
def __binary_search_key(self, key: K) -> int:
9094
# TODO: special sort order for strings
9195
low, high = 0, (len(self.__data) // 2) - 1
9296
while low <= high:
@@ -100,20 +104,20 @@ def __binary_search_key(self, key: K) -> int:
100104
return mid
101105
return -(low + 1)
102106

103-
def plus(self, key: K, value: V) -> 'ArrayMap[K, V]':
104-
index = self.__binary_search_key(key)
107+
def plus(self, key: K, value: V) -> "ArrayMap[K, V]":
108+
index = self.__binary_search_key(key)
105109
if index >= 0:
106110
raise ValueError("Key already exists")
107111
insert_at = -(index + 1)
108112
new_data = self.__data[:]
109-
new_data[insert_at * 2:insert_at * 2] = [key, value]
113+
new_data[insert_at * 2 : insert_at * 2] = [key, value]
110114
return ArrayMap(new_data)
111115

112-
def minus_sorted_indices(self, indicesToRemove: List[int]) -> 'ArrayMap[K, V]':
116+
def minus_sorted_indices(self, indicesToRemove: List[int]) -> "ArrayMap[K, V]":
113117
if not indicesToRemove:
114118
return self
115119
newData = []
116120
for i in range(0, len(self.__data), 2):
117121
if i // 2 not in indicesToRemove:
118-
newData.extend(self.__data[i:i + 2])
122+
newData.extend(self.__data[i : i + 2])
119123
return ArrayMap(newData)
Lines changed: 30 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,23 @@
1-
from typing import Optional
2-
from typing import Union
1+
from typing import Optional
2+
from typing import Union
33
from collections import Counter
44

5+
56
class Slice:
67
"""Represents a slice of a base string from startIndex to endIndex."""
78

8-
def __init__(self, base: str, startIndex: int = 0, endIndex: Optional[int] = None) -> None:
9+
def __init__(
10+
self, base: str, startIndex: int = 0, endIndex: Optional[int] = None
11+
) -> None:
912
self.base = base
1013
self.base = base
1114
self.startIndex = startIndex
1215
self.endIndex = endIndex if endIndex is not None else len(base)
1316

14-
assert 0 <= self.startIndex <= self.endIndex <= len(base), "Invalid start or end index"
15-
17+
assert (
18+
0 <= self.startIndex <= self.endIndex <= len(base)
19+
), "Invalid start or end index"
20+
1621
def __len__(self) -> int:
1722
return self.endIndex - self.startIndex
1823

@@ -21,10 +26,10 @@ def __getitem__(self, index: int) -> str:
2126
raise IndexError("Index out of range")
2227
return self.base[self.startIndex + index]
2328

24-
def subSequence(self, start: int, end: int) -> 'Slice':
29+
def subSequence(self, start: int, end: int) -> "Slice":
2530
return Slice(self.base, self.startIndex + start, self.startIndex + end)
2631

27-
def trim(self) -> 'Slice':
32+
def trim(self) -> "Slice":
2833
start, end = 0, len(self)
2934
while start < end and self[start].isspace():
3035
start += 1
@@ -33,9 +38,9 @@ def trim(self) -> 'Slice':
3338
return self.subSequence(start, end) if start > 0 or end < len(self) else self
3439

3540
def __str__(self) -> str:
36-
return self.base[self.startIndex:self.endIndex]
41+
return self.base[self.startIndex : self.endIndex]
3742

38-
def sameAs(self, other: Union['Slice', str]) -> bool:
43+
def sameAs(self, other: Union["Slice", str]) -> bool:
3944
if isinstance(other, Slice):
4045
return str(self) == str(other)
4146
elif isinstance(other, str):
@@ -48,18 +53,24 @@ def sameAs(self, other: Union['Slice', str]) -> bool:
4853
return False
4954

5055
def indexOf(self, lookingFor: str, startOffset: int = 0) -> int:
51-
result = self.base.find(lookingFor, self.startIndex + startOffset, self.endIndex)
56+
result = self.base.find(
57+
lookingFor, self.startIndex + startOffset, self.endIndex
58+
)
5259
return -1 if result == -1 else result - self.startIndex
5360

54-
def unixLine(self, count: int) -> 'Slice':
61+
def unixLine(self, count: int) -> "Slice":
5562
assert count > 0, "Count must be positive"
5663
lineStart = 0
5764
for i in range(1, count):
58-
lineStart = self.indexOf('\n', lineStart)
65+
lineStart = self.indexOf("\n", lineStart)
5966
assert lineStart >= 0, f"This string has only {i - 1} lines, not {count}"
6067
lineStart += 1
61-
lineEnd = self.indexOf('\n', lineStart)
62-
return Slice(self.base, self.startIndex + lineStart, self.endIndex if lineEnd == -1 else self.startIndex + lineEnd)
68+
lineEnd = self.indexOf("\n", lineStart)
69+
return Slice(
70+
self.base,
71+
self.startIndex + lineStart,
72+
self.endIndex if lineEnd == -1 else self.startIndex + lineEnd,
73+
)
6374

6475
def __eq__(self, other: object) -> bool:
6576
if self is other:
@@ -75,10 +86,10 @@ def __hash__(self) -> int:
7586
return h
7687

7788
def replaceSelfWith(self, s: str) -> str:
78-
return self.base[:self.startIndex] + s + self.base[self.endIndex:]
79-
89+
return self.base[: self.startIndex] + s + self.base[self.endIndex :]
90+
8091
def count(self, char: str) -> int:
81-
return Counter(self.base[self.startIndex:self.endIndex])[char]
82-
92+
return Counter(self.base[self.startIndex : self.endIndex])[char]
93+
8394
def baseLineAtOffset(self, index: int) -> int:
84-
return 1 + Slice(self.base, 0, index).count('\n')
95+
return 1 + Slice(self.base, 0, index).count("\n")
Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,2 @@
11
from .LineReader import LineReader as LineReader
22
from .Slice import Slice as Slice
3-

python/selfie-lib/tests/ArrayMap_test.py

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import pytest
22
from selfie_lib.ArrayMap import ArrayMap
33

4+
45
def assertEmpty(map):
56
assert len(map) == 0
67
assert list(map.keys()) == []
@@ -11,6 +12,7 @@ def assertEmpty(map):
1112
assert map == {}
1213
assert map == ArrayMap.empty()
1314

15+
1416
def assertSingle(map, key, value):
1517
assert len(map) == 1
1618
assert set(map.keys()) == {key}
@@ -22,6 +24,7 @@ def assertSingle(map, key, value):
2224
assert map == {key: value}
2325
assert map == ArrayMap.empty().plus(key, value)
2426

27+
2528
def assertDouble(map, key1, value1, key2, value2):
2629
assert len(map) == 2
2730
assert set(map.keys()) == {key1, key2}
@@ -36,6 +39,7 @@ def assertDouble(map, key1, value1, key2, value2):
3639
assert map == ArrayMap.empty().plus(key1, value1).plus(key2, value2)
3740
assert map == ArrayMap.empty().plus(key2, value2).plus(key1, value1)
3841

42+
3943
def assertTriple(map, key1, value1, key2, value2, key3, value3):
4044
assert len(map) == 3
4145
assert set(map.keys()) == {key1, key2, key3}
@@ -47,17 +51,22 @@ def assertTriple(map, key1, value1, key2, value2, key3, value3):
4751
with pytest.raises(KeyError):
4852
_ = map[key1 + "blah"]
4953
assert map == {key1: value1, key2: value2, key3: value3}
50-
assert map == ArrayMap.empty().plus(key1, value1).plus(key2, value2).plus(key3, value3)
54+
assert map == ArrayMap.empty().plus(key1, value1).plus(key2, value2).plus(
55+
key3, value3
56+
)
57+
5158

5259
def test_empty():
5360
assertEmpty(ArrayMap.empty())
5461

62+
5563
def test_single():
5664
empty = ArrayMap.empty()
5765
single = empty.plus("one", "1")
5866
assertEmpty(empty)
5967
assertSingle(single, "one", "1")
6068

69+
6170
def test_double():
6271
empty = ArrayMap.empty()
6372
single = empty.plus("one", "1")
@@ -71,19 +80,28 @@ def test_double():
7180
single.plus("one", "2")
7281
assert str(context.value) == "Key already exists"
7382

83+
7484
def test_triple():
7585
triple = ArrayMap.empty().plus("1", "one").plus("2", "two").plus("3", "three")
7686
assertTriple(triple, "1", "one", "2", "two", "3", "three")
7787

88+
7889
def test_multi():
7990
test_triple() # Calling another test function directly is unusual but works
8091
triple = ArrayMap.empty().plus("2", "two").plus("3", "three").plus("1", "one")
8192
assertTriple(triple, "1", "one", "2", "two", "3", "three")
8293
triple = ArrayMap.empty().plus("3", "three").plus("1", "one").plus("2", "two")
8394
assertTriple(triple, "1", "one", "2", "two", "3", "three")
8495

96+
8597
def test_minus_sorted_indices():
86-
initial_map = ArrayMap.empty().plus("1", "one").plus("2", "two").plus("3", "three").plus("4", "four")
98+
initial_map = (
99+
ArrayMap.empty()
100+
.plus("1", "one")
101+
.plus("2", "two")
102+
.plus("3", "three")
103+
.plus("4", "four")
104+
)
87105
modified_map = initial_map.minus_sorted_indices([1, 3])
88106
assert len(modified_map) == 2
89107
assert list(modified_map.keys()) == ["1", "3"]
@@ -94,6 +112,7 @@ def test_minus_sorted_indices():
94112
_ = modified_map["4"]
95113
assert modified_map == {"1": "one", "3": "three"}
96114

115+
97116
def test_plus_with_existing_keys():
98117
map_with_duplicates = ArrayMap.empty().plus("a", "alpha").plus("b", "beta")
99118
with pytest.raises(ValueError):
@@ -103,11 +122,14 @@ def test_plus_with_existing_keys():
103122
assert updated_map["a"] == "alpha"
104123
assert updated_map["b"] == "beta"
105124
assert updated_map["c"] == "gamma"
106-
modified_map = map_with_duplicates.minus_sorted_indices([0]).plus("a", "updated alpha")
125+
modified_map = map_with_duplicates.minus_sorted_indices([0]).plus(
126+
"a", "updated alpha"
127+
)
107128
assert len(modified_map) == 2
108129
assert modified_map["a"] == "updated alpha"
109130
assert modified_map["b"] == "beta"
110131

132+
111133
def test_map_length():
112134
map = ArrayMap.empty()
113135
assert len(map) == 0, "Length should be 0 for an empty map"
@@ -119,7 +141,7 @@ def test_map_length():
119141
assert len(map) == 3, "Length should be 3 after adding a third item"
120142
map = map.minus_sorted_indices([1])
121143
assert len(map) == 2, "Length should be 2 after removing one item"
122-
map = map.minus_sorted_indices([0])
144+
map = map.minus_sorted_indices([0])
123145
assert len(map) == 1, "Length should be 1 after removing another item"
124-
map = map.minus_sorted_indices([0])
146+
map = map.minus_sorted_indices([0])
125147
assert len(map) == 0, "Length should be 0 after removing all items"

0 commit comments

Comments
 (0)