Skip to content

Commit 9861781

Browse files
committed
Add type annotations to a few files
1 parent 5eb31eb commit 9861781

File tree

5 files changed

+55
-52
lines changed

5 files changed

+55
-52
lines changed

bpython/_internal.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,20 @@
88

99

1010
class _Helper:
11-
def __init__(self):
11+
def __init__(self) -> None:
1212
if hasattr(pydoc.Helper, "output"):
1313
# See issue #228
1414
self.helper = pydoc.Helper(sys.stdin, None)
1515
else:
1616
self.helper = pydoc.Helper(sys.stdin, sys.stdout)
1717

18-
def __repr__(self):
18+
def __repr__(self) -> str:
1919
return (
2020
"Type help() for interactive help, "
2121
"or help(object) for help about object."
2222
)
2323

24-
def __call__(self, *args, **kwargs):
24+
def __call__(self, *args, **kwargs) -> None:
2525
self.helper(*args, **kwargs)
2626

2727

bpython/args.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
"""
2727

2828
import argparse
29+
from typing import Tuple
2930
import curtsies
3031
import cwcwidth
3132
import greenlet
@@ -53,7 +54,7 @@ def error(self, msg):
5354
raise ArgumentParserFailed()
5455

5556

56-
def version_banner(base="bpython"):
57+
def version_banner(base="bpython") -> str:
5758
return _("{} version {} on top of Python {} {}").format(
5859
base,
5960
__version__,
@@ -62,11 +63,11 @@ def version_banner(base="bpython"):
6263
)
6364

6465

65-
def copyright_banner():
66+
def copyright_banner() -> str:
6667
return _("{} See AUTHORS.rst for details.").format(__copyright__)
6768

6869

69-
def parse(args, extras=None, ignore_stdin=False):
70+
def parse(args, extras=None, ignore_stdin=False) -> Tuple:
7071
"""Receive an argument list - if None, use sys.argv - parse all args and
7172
take appropriate action. Also receive optional extra argument: this should
7273
be a tuple of (title, description, callback)

bpython/autocomplete.py

Lines changed: 36 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
import builtins
3434

3535
from enum import Enum
36+
from typing import Any, Dict, Iterator, List, Match, NoReturn, Set, Union
3637
from . import inspection
3738
from . import line as lineparts
3839
from .line import LinePart
@@ -48,7 +49,7 @@ class AutocompleteModes(Enum):
4849
FUZZY = "fuzzy"
4950

5051
@classmethod
51-
def from_string(cls, value):
52+
def from_string(cls, value) -> Union[Any, None]:
5253
if value.upper() in cls.__members__:
5354
return cls.__members__[value.upper()]
5455
return None
@@ -161,11 +162,11 @@ def from_string(cls, value):
161162
KEYWORDS = frozenset(keyword.kwlist)
162163

163164

164-
def after_last_dot(name):
165+
def after_last_dot(name: str) -> str:
165166
return name.rstrip(".").rsplit(".")[-1]
166167

167168

168-
def few_enough_underscores(current, match):
169+
def few_enough_underscores(current, match) -> bool:
169170
"""Returns whether match should be shown based on current
170171
171172
if current is _, True if match starts with 0 or 1 underscore
@@ -179,19 +180,19 @@ def few_enough_underscores(current, match):
179180
return not match.startswith("_")
180181

181182

182-
def method_match_none(word, size, text):
183+
def method_match_none(word, size, text) -> False:
183184
return False
184185

185186

186-
def method_match_simple(word, size, text):
187+
def method_match_simple(word, size, text) -> bool:
187188
return word[:size] == text
188189

189190

190-
def method_match_substring(word, size, text):
191+
def method_match_substring(word, size, text) -> bool:
191192
return text in word
192193

193194

194-
def method_match_fuzzy(word, size, text):
195+
def method_match_fuzzy(word, size, text) -> Union[Match, None]:
195196
s = r".*%s.*" % ".*".join(list(text))
196197
return re.search(s, word)
197198

@@ -207,11 +208,11 @@ def method_match_fuzzy(word, size, text):
207208
class BaseCompletionType:
208209
"""Describes different completion types"""
209210

210-
def __init__(self, shown_before_tab=True, mode=AutocompleteModes.SIMPLE):
211+
def __init__(self, shown_before_tab: bool=True, mode=AutocompleteModes.SIMPLE) -> None:
211212
self._shown_before_tab = shown_before_tab
212213
self.method_match = MODES_MAP[mode]
213214

214-
def matches(self, cursor_offset, line, **kwargs):
215+
def matches(self, cursor_offset, line, **kwargs) -> NoReturn:
215216
"""Returns a list of possible matches given a line and cursor, or None
216217
if this completion type isn't applicable.
217218
@@ -229,7 +230,7 @@ def matches(self, cursor_offset, line, **kwargs):
229230
"""
230231
raise NotImplementedError
231232

232-
def locate(self, cursor_offset, line):
233+
def locate(self, cursor_offset, line) -> NoReturn:
233234
"""Returns a Linepart namedtuple instance or None given cursor and line
234235
235236
A Linepart namedtuple contains a start, stop, and word. None is
@@ -240,15 +241,15 @@ def locate(self, cursor_offset, line):
240241
def format(self, word):
241242
return word
242243

243-
def substitute(self, cursor_offset, line, match):
244+
def substitute(self, cursor_offset, line, match) -> NoReturn:
244245
"""Returns a cursor offset and line with match swapped in"""
245246
lpart = self.locate(cursor_offset, line)
246247
offset = lpart.start + len(match)
247248
changed_line = line[: lpart.start] + match + line[lpart.stop :]
248249
return offset, changed_line
249250

250251
@property
251-
def shown_before_tab(self):
252+
def shown_before_tab(self) -> bool:
252253
"""Whether suggestions should be shown before the user hits tab, or only
253254
once that has happened."""
254255
return self._shown_before_tab
@@ -257,7 +258,7 @@ def shown_before_tab(self):
257258
class CumulativeCompleter(BaseCompletionType):
258259
"""Returns combined matches from several completers"""
259260

260-
def __init__(self, completers, mode=AutocompleteModes.SIMPLE):
261+
def __init__(self, completers, mode=AutocompleteModes.SIMPLE) -> None:
261262
if not completers:
262263
raise ValueError(
263264
"CumulativeCompleter requires at least one completer"
@@ -266,7 +267,7 @@ def __init__(self, completers, mode=AutocompleteModes.SIMPLE):
266267

267268
super().__init__(True, mode)
268269

269-
def locate(self, current_offset, line):
270+
def locate(self, current_offset, line) -> Union[None, NoReturn]:
270271
for completer in self._completers:
271272
return_value = completer.locate(current_offset, line)
272273
if return_value is not None:
@@ -275,7 +276,7 @@ def locate(self, current_offset, line):
275276
def format(self, word):
276277
return self._completers[0].format(word)
277278

278-
def matches(self, cursor_offset, line, **kwargs):
279+
def matches(self, cursor_offset, line, **kwargs) -> Union[None, Set]:
279280
return_value = None
280281
all_matches = set()
281282
for completer in self._completers:
@@ -308,10 +309,10 @@ class FilenameCompletion(BaseCompletionType):
308309
def __init__(self, mode=AutocompleteModes.SIMPLE):
309310
super().__init__(False, mode)
310311

311-
def safe_glob(self, pathname):
312+
def safe_glob(self, pathname) -> Iterator:
312313
return glob.iglob(glob.escape(pathname) + "*")
313314

314-
def matches(self, cursor_offset, line, **kwargs):
315+
def matches(self, cursor_offset, line, **kwargs) -> Union[None, set]:
315316
cs = lineparts.current_string(cursor_offset, line)
316317
if cs is None:
317318
return None
@@ -341,7 +342,7 @@ class AttrCompletion(BaseCompletionType):
341342

342343
attr_matches_re = LazyReCompile(r"(\w+(\.\w+)*)\.(\w*)")
343344

344-
def matches(self, cursor_offset, line, **kwargs):
345+
def matches(self, cursor_offset, line, **kwargs) -> Union[None, Dict]:
345346
if "locals_" not in kwargs:
346347
return None
347348
locals_ = kwargs["locals_"]
@@ -377,7 +378,7 @@ def locate(self, current_offset, line):
377378
def format(self, word):
378379
return after_last_dot(word)
379380

380-
def attr_matches(self, text, namespace):
381+
def attr_matches(self, text, namespace) -> List:
381382
"""Taken from rlcompleter.py and bent to my will."""
382383

383384
m = self.attr_matches_re.match(text)
@@ -396,7 +397,7 @@ def attr_matches(self, text, namespace):
396397
matches = self.attr_lookup(obj, expr, attr)
397398
return matches
398399

399-
def attr_lookup(self, obj, expr, attr):
400+
def attr_lookup(self, obj, expr, attr) -> List:
400401
"""Second half of attr_matches."""
401402
words = self.list_attributes(obj)
402403
if inspection.hasattr_safe(obj, "__class__"):
@@ -416,15 +417,15 @@ def attr_lookup(self, obj, expr, attr):
416417
matches.append(f"{expr}.{word}")
417418
return matches
418419

419-
def list_attributes(self, obj):
420+
def list_attributes(self, obj) -> List[str]:
420421
# TODO: re-implement dir using getattr_static to avoid using
421422
# AttrCleaner here?
422423
with inspection.AttrCleaner(obj):
423424
return dir(obj)
424425

425426

426427
class DictKeyCompletion(BaseCompletionType):
427-
def matches(self, cursor_offset, line, **kwargs):
428+
def matches(self, cursor_offset, line, **kwargs) -> Union[None, Dict]:
428429
if "locals_" not in kwargs:
429430
return None
430431
locals_ = kwargs["locals_"]
@@ -445,15 +446,15 @@ def matches(self, cursor_offset, line, **kwargs):
445446
else:
446447
return None
447448

448-
def locate(self, current_offset, line):
449+
def locate(self, current_offset, line) -> Union[LinePart, None]:
449450
return lineparts.current_dict_key(current_offset, line)
450451

451452
def format(self, match):
452453
return match[:-1]
453454

454455

455456
class MagicMethodCompletion(BaseCompletionType):
456-
def matches(self, cursor_offset, line, **kwargs):
457+
def matches(self, cursor_offset, line, **kwargs) -> Union[None, Dict]:
457458
if "current_block" not in kwargs:
458459
return None
459460
current_block = kwargs["current_block"]
@@ -465,12 +466,12 @@ def matches(self, cursor_offset, line, **kwargs):
465466
return None
466467
return {name for name in MAGIC_METHODS if name.startswith(r.word)}
467468

468-
def locate(self, current_offset, line):
469+
def locate(self, current_offset, line) -> Union[LinePart, None]:
469470
return lineparts.current_method_definition_name(current_offset, line)
470471

471472

472473
class GlobalCompletion(BaseCompletionType):
473-
def matches(self, cursor_offset, line, **kwargs):
474+
def matches(self, cursor_offset, line, **kwargs) -> Union[Set, None]:
474475
"""Compute matches when text is a simple name.
475476
Return a list of all keywords, built-in functions and names currently
476477
defined in self.namespace that match.
@@ -500,12 +501,12 @@ def matches(self, cursor_offset, line, **kwargs):
500501
matches.add(_callable_postfix(val, word))
501502
return matches if matches else None
502503

503-
def locate(self, current_offset, line):
504+
def locate(self, current_offset, line) -> Union[LinePart, None]:
504505
return lineparts.current_single_word(current_offset, line)
505506

506507

507508
class ParameterNameCompletion(BaseCompletionType):
508-
def matches(self, cursor_offset, line, **kwargs):
509+
def matches(self, cursor_offset, line, **kwargs) -> Union[None, Dict]:
509510
if "argspec" not in kwargs:
510511
return None
511512
argspec = kwargs["argspec"]
@@ -526,16 +527,16 @@ def matches(self, cursor_offset, line, **kwargs):
526527
)
527528
return matches if matches else None
528529

529-
def locate(self, current_offset, line):
530+
def locate(self, current_offset, line) -> Union[LinePart, None]:
530531
return lineparts.current_word(current_offset, line)
531532

532533

533534
class ExpressionAttributeCompletion(AttrCompletion):
534535
# could replace attr completion as a more general case with some work
535-
def locate(self, current_offset, line):
536+
def locate(self, current_offset, line) -> Union[LinePart, None]:
536537
return lineparts.current_expression_attribute(current_offset, line)
537538

538-
def matches(self, cursor_offset, line, **kwargs):
539+
def matches(self, cursor_offset, line, **kwargs) -> Union[Set, Dict, None]:
539540
if "locals_" not in kwargs:
540541
return None
541542
locals_ = kwargs["locals_"]
@@ -560,14 +561,14 @@ def matches(self, cursor_offset, line, **kwargs):
560561
except ImportError:
561562

562563
class MultilineJediCompletion(BaseCompletionType):
563-
def matches(self, cursor_offset, line, **kwargs):
564+
def matches(self, cursor_offset, line, **kwargs) -> None:
564565
return None
565566

566567

567568
else:
568569

569570
class JediCompletion(BaseCompletionType):
570-
def matches(self, cursor_offset, line, **kwargs):
571+
def matches(self, cursor_offset, line, **kwargs) -> Union[None, Dict]:
571572
if "history" not in kwargs:
572573
return None
573574
history = kwargs["history"]
@@ -607,13 +608,13 @@ def matches(self, cursor_offset, line, **kwargs):
607608
# case-sensitive matches only
608609
return {m for m in matches if m.startswith(first_letter)}
609610

610-
def locate(self, cursor_offset, line):
611+
def locate(self, cursor_offset, line) -> LinePart:
611612
start = self._orig_start
612613
end = cursor_offset
613614
return LinePart(start, end, line[start:end])
614615

615616
class MultilineJediCompletion(JediCompletion):
616-
def matches(self, cursor_offset, line, **kwargs):
617+
def matches(self, cursor_offset, line, **kwargs) -> Union[Dict, None]:
617618
if "current_block" not in kwargs or "history" not in kwargs:
618619
return None
619620
current_block = kwargs["current_block"]

0 commit comments

Comments
 (0)