Skip to content

Commit ae67b5a

Browse files
committed
Add type annotations
1 parent 447bede commit ae67b5a

File tree

2 files changed

+81
-44
lines changed

2 files changed

+81
-44
lines changed

bpython/filelock.py

Lines changed: 29 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@
2020
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
2121
# THE SOFTWARE.
2222

23+
from typing import Optional, Type, IO
24+
from types import TracebackType
25+
2326
has_fcntl = True
2427
try:
2528
import fcntl
@@ -38,57 +41,63 @@
3841
class BaseLock:
3942
"""Base class for file locking"""
4043

41-
def __init__(self, fileobj=None):
42-
self.fileobj = fileobj
44+
def __init__(self) -> None:
4345
self.locked = False
4446

45-
def acquire(self):
47+
def acquire(self) -> None:
4648
pass
4749

48-
def release(self):
50+
def release(self) -> None:
4951
pass
5052

51-
def __enter__(self):
53+
def __enter__(self) -> "BaseLock":
5254
self.acquire()
5355
return self
5456

55-
def __exit__(self, *args):
57+
def __exit__(
58+
self,
59+
exc_type: Optional[Type[BaseException]],
60+
exc: Optional[BaseException],
61+
exc_tb: Optional[TracebackType],
62+
) -> None:
5663
if self.locked:
5764
self.release()
5865

59-
def __del__(self):
66+
def __del__(self) -> None:
6067
if self.locked:
6168
self.release()
6269

6370

6471
class UnixFileLock(BaseLock):
6572
"""Simple file locking for Unix using fcntl"""
6673

67-
def __init__(self, fileobj, mode=0):
68-
super().__init__(fileobj)
74+
def __init__(self, fileobj, mode: int = 0) -> None:
75+
super().__init__()
76+
self.fileobj = fileobj
6977
self.mode = mode | fcntl.LOCK_EX
7078

71-
def acquire(self):
79+
def acquire(self) -> None:
7280
try:
7381
fcntl.flock(self.fileobj, self.mode)
7482
self.locked = True
7583
except OSError as e:
7684
if e.errno != errno.ENOLCK:
7785
raise e
7886

79-
def release(self):
87+
def release(self) -> None:
8088
self.locked = False
8189
fcntl.flock(self.fileobj, fcntl.LOCK_UN)
8290

8391

8492
class WindowsFileLock(BaseLock):
8593
"""Simple file locking for Windows using msvcrt"""
8694

87-
def __init__(self, filename):
95+
def __init__(self, filename: str) -> None:
8896
super().__init__()
8997
self.filename = f"{filename}.lock"
98+
self.fileobj = -1
9099

91-
def acquire(self):
100+
def acquire(self) -> None:
92101
# create a lock file and lock it
93102
self.fileobj = os.open(
94103
self.filename, os.O_RDWR | os.O_CREAT | os.O_TRUNC
@@ -97,26 +106,28 @@ def acquire(self):
97106

98107
self.locked = True
99108

100-
def release(self):
109+
def release(self) -> None:
101110
self.locked = False
102111

103112
# unlock lock file and remove it
104113
msvcrt.locking(self.fileobj, msvcrt.LK_UNLCK, 1)
105114
os.close(self.fileobj)
106-
self.fileobj = None
115+
self.fileobj = -1
107116

108117
try:
109118
os.remove(self.filename)
110119
except OSError:
111120
pass
112121

113122

114-
def FileLock(fileobj, mode=0, filename=None):
123+
def FileLock(
124+
fileobj: IO, mode: int = 0, filename: Optional[str] = None
125+
) -> BaseLock:
115126
if has_fcntl:
116127
return UnixFileLock(fileobj, mode)
117-
elif has_msvcrt:
128+
elif has_msvcrt and filename is not None:
118129
return WindowsFileLock(filename)
119-
return BaseLock(fileobj)
130+
return BaseLock()
120131

121132

122133
# vim: sw=4 ts=4 sts=4 ai et

bpython/history.py

Lines changed: 52 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# The MIT License
22
#
33
# Copyright (c) 2009 the bpython authors.
4-
# Copyright (c) 2012,2015 Sebastian Ramacher
4+
# Copyright (c) 2012-2021 Sebastian Ramacher
55
#
66
# Permission is hereby granted, free of charge, to any person obtaining a copy
77
# of this software and associated documentation files (the "Software"), to deal
@@ -24,6 +24,7 @@
2424
import os
2525
import stat
2626
from itertools import islice
27+
from typing import Iterable, Optional, List, TextIO
2728

2829
from .translations import _
2930
from .filelock import FileLock
@@ -32,7 +33,12 @@
3233
class History:
3334
"""Stores readline-style history and current place in it"""
3435

35-
def __init__(self, entries=None, duplicates=True, hist_size=100):
36+
def __init__(
37+
self,
38+
entries: Optional[Iterable[str]] = None,
39+
duplicates: bool = True,
40+
hist_size: int = 100,
41+
) -> None:
3642
if entries is None:
3743
self.entries = [""]
3844
else:
@@ -45,10 +51,10 @@ def __init__(self, entries=None, duplicates=True, hist_size=100):
4551
self.duplicates = duplicates
4652
self.hist_size = hist_size
4753

48-
def append(self, line):
54+
def append(self, line: str) -> None:
4955
self.append_to(self.entries, line)
5056

51-
def append_to(self, entries, line):
57+
def append_to(self, entries: List[str], line: str) -> None:
5258
line = line.rstrip("\n")
5359
if line:
5460
if not self.duplicates:
@@ -60,15 +66,19 @@ def append_to(self, entries, line):
6066
pass
6167
entries.append(line)
6268

63-
def first(self):
69+
def first(self) -> str:
6470
"""Move back to the beginning of the history."""
6571
if not self.is_at_end:
6672
self.index = len(self.entries)
6773
return self.entries[-self.index]
6874

6975
def back(
70-
self, start=True, search=False, target=None, include_current=False
71-
):
76+
self,
77+
start: bool = True,
78+
search: bool = False,
79+
target: Optional[str] = None,
80+
include_current: bool = False,
81+
) -> str:
7282
"""Move one step back in the history."""
7383
if target is None:
7484
target = self.saved_line
@@ -84,23 +94,27 @@ def back(
8494
return self.entry
8595

8696
@property
87-
def entry(self):
97+
def entry(self) -> str:
8898
"""The current entry, which may be the saved line"""
8999
return self.entries[-self.index] if self.index else self.saved_line
90100

91101
@property
92-
def entries_by_index(self):
102+
def entries_by_index(self) -> List[str]:
93103
return list(reversed(self.entries + [self.saved_line]))
94104

95-
def find_match_backward(self, search_term, include_current=False):
105+
def find_match_backward(
106+
self, search_term: str, include_current: bool = False
107+
) -> int:
96108
add = 0 if include_current else 1
97109
start = self.index + add
98110
for idx, val in enumerate(islice(self.entries_by_index, start, None)):
99111
if val.startswith(search_term):
100112
return idx + add
101113
return 0
102114

103-
def find_partial_match_backward(self, search_term, include_current=False):
115+
def find_partial_match_backward(
116+
self, search_term: str, include_current: bool = False
117+
) -> int:
104118
add = 0 if include_current else 1
105119
start = self.index + add
106120
for idx, val in enumerate(islice(self.entries_by_index, start, None)):
@@ -109,8 +123,12 @@ def find_partial_match_backward(self, search_term, include_current=False):
109123
return 0
110124

111125
def forward(
112-
self, start=True, search=False, target=None, include_current=False
113-
):
126+
self,
127+
start: bool = True,
128+
search: bool = False,
129+
target: Optional[str] = None,
130+
include_current: bool = False,
131+
) -> str:
114132
"""Move one step forward in the history."""
115133
if target is None:
116134
target = self.saved_line
@@ -128,7 +146,9 @@ def forward(
128146
self.index = 0
129147
return self.saved_line
130148

131-
def find_match_forward(self, search_term, include_current=False):
149+
def find_match_forward(
150+
self, search_term: str, include_current: bool = False
151+
) -> int:
132152
add = 0 if include_current else 1
133153
end = max(0, self.index - (1 - add))
134154
for idx in range(end):
@@ -137,7 +157,9 @@ def find_match_forward(self, search_term, include_current=False):
137157
return idx + (0 if include_current else 1)
138158
return self.index
139159

140-
def find_partial_match_forward(self, search_term, include_current=False):
160+
def find_partial_match_forward(
161+
self, search_term: str, include_current: bool = False
162+
) -> int:
141163
add = 0 if include_current else 1
142164
end = max(0, self.index - (1 - add))
143165
for idx in range(end):
@@ -146,40 +168,40 @@ def find_partial_match_forward(self, search_term, include_current=False):
146168
return idx + add
147169
return self.index
148170

149-
def last(self):
171+
def last(self) -> str:
150172
"""Move forward to the end of the history."""
151173
if not self.is_at_start:
152174
self.index = 0
153175
return self.entries[0]
154176

155177
@property
156-
def is_at_end(self):
178+
def is_at_end(self) -> bool:
157179
return self.index >= len(self.entries) or self.index == -1
158180

159181
@property
160-
def is_at_start(self):
182+
def is_at_start(self) -> bool:
161183
return self.index == 0
162184

163-
def enter(self, line):
185+
def enter(self, line: str) -> None:
164186
if self.index == 0:
165187
self.saved_line = line
166188

167-
def reset(self):
189+
def reset(self) -> None:
168190
self.index = 0
169191
self.saved_line = ""
170192

171-
def load(self, filename, encoding):
193+
def load(self, filename: str, encoding: str) -> None:
172194
with open(filename, encoding=encoding, errors="ignore") as hfile:
173195
with FileLock(hfile, filename=filename):
174196
self.entries = self.load_from(hfile)
175197

176-
def load_from(self, fd):
177-
entries = []
198+
def load_from(self, fd: TextIO) -> List[str]:
199+
entries: List[str] = []
178200
for line in fd:
179201
self.append_to(entries, line)
180202
return entries if len(entries) else [""]
181203

182-
def save(self, filename, encoding, lines=0):
204+
def save(self, filename: str, encoding: str, lines: int = 0) -> None:
183205
fd = os.open(
184206
filename,
185207
os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
@@ -189,14 +211,18 @@ def save(self, filename, encoding, lines=0):
189211
with FileLock(hfile, filename=filename):
190212
self.save_to(hfile, self.entries, lines)
191213

192-
def save_to(self, fd, entries=None, lines=0):
214+
def save_to(
215+
self, fd: TextIO, entries: Optional[List[str]] = None, lines: int = 0
216+
) -> None:
193217
if entries is None:
194218
entries = self.entries
195219
for line in entries[-lines:]:
196220
fd.write(line)
197221
fd.write("\n")
198222

199-
def append_reload_and_write(self, s, filename, encoding):
223+
def append_reload_and_write(
224+
self, s: str, filename: str, encoding: str
225+
) -> None:
200226
if not self.hist_size:
201227
return self.append(s)
202228

0 commit comments

Comments
 (0)