Skip to content

Commit 48d26a3

Browse files
committed
More mypy validation changes. cmd2.py is nearly fully mypy compliant now.
1 parent 33951e8 commit 48d26a3

File tree

7 files changed

+91
-69
lines changed

7 files changed

+91
-69
lines changed

cmd2/__init__.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@
33
# flake8: noqa F401
44
"""This simply imports certain things for backwards compatibility."""
55

6-
try:
7-
# For python 3.8 and later
6+
import sys
7+
8+
# For python 3.8 and late
9+
if sys.version_info >= (3, 8):
810
import importlib.metadata as importlib_metadata
9-
except ImportError:
11+
else:
1012
# For everyone else
1113
import importlib_metadata
1214
try:

cmd2/argparse_custom.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,6 @@ def my_completer(self, text, line, begidx, endidx, arg_tokens)
215215
Tuple,
216216
Type,
217217
Union,
218-
cast,
219218
)
220219

221220
from . import (
@@ -279,7 +278,7 @@ class CompletionItem(str):
279278
"""
280279

281280
def __new__(cls, value: object, *args: Any, **kwargs: Any) -> 'CompletionItem':
282-
return cast(CompletionItem, super(CompletionItem, cls).__new__(cls, value)) # type: ignore [call-arg]
281+
return super(CompletionItem, cls).__new__(cls, value)
283282

284283
# noinspection PyUnusedLocal
285284
def __init__(self, value: object, desc: str = '', *args: Any) -> None:
@@ -887,7 +886,7 @@ def __init__(
887886
description=description,
888887
epilog=epilog,
889888
parents=parents if parents else [],
890-
formatter_class=formatter_class,
889+
formatter_class=formatter_class, # type: ignore[arg-type]
891890
prefix_chars=prefix_chars,
892891
fromfile_prefix_chars=fromfile_prefix_chars,
893892
argument_default=argument_default,
@@ -930,7 +929,7 @@ def format_help(self) -> str:
930929
formatter = self._get_formatter()
931930

932931
# usage
933-
formatter.add_usage(self.usage, self._actions, self._mutually_exclusive_groups)
932+
formatter.add_usage(self.usage, self._actions, self._mutually_exclusive_groups) # type: ignore[arg-type]
934933

935934
# description
936935
formatter.add_text(self.description)

cmd2/cmd2.py

Lines changed: 57 additions & 49 deletions
Large diffs are not rendered by default.

cmd2/decorators.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ def _arg_swap(args: Union[Tuple[Any], List[Any]], search_arg: Any, *replace_arg:
108108

109109
def with_argument_list(
110110
func_arg: Optional[Callable[[List[str]], Optional[bool]]] = None, *, preserve_quotes: bool = False
111-
) -> Union[Callable[[List[str]], Optional[bool]],]:
111+
) -> Union[Callable[[List[str]], Optional[bool]]]:
112112
"""
113113
A decorator to alter the arguments passed to a ``do_*`` method. Default
114114
passes a string of whatever the user typed. With this decorator, the

cmd2/rl_utils.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,13 @@
1010
# Prefer statically linked gnureadline if available (for macOS compatibility due to issues with libedit)
1111
try:
1212
# noinspection PyPackageRequirements
13-
import gnureadline as readline
13+
import gnureadline as readline # type: ignore[import]
1414
except ImportError:
1515
# Try to import readline, but allow failure for convenience in Windows unit testing
1616
# Note: If this actually fails, you should install readline on Linux or Mac or pyreadline on Windows
1717
try:
1818
# noinspection PyUnresolvedReferences
19-
import readline
19+
import readline # type: ignore[no-redef]
2020
except ImportError: # pragma: no cover
2121
pass
2222

@@ -182,7 +182,7 @@ def rl_get_point() -> int: # pragma: no cover
182182
return ctypes.c_int.in_dll(readline_lib, "rl_point").value
183183

184184
elif rl_type == RlType.PYREADLINE:
185-
return readline.rl.mode.l_buffer.point
185+
return int(readline.rl.mode.l_buffer.point)
186186

187187
else:
188188
return 0

cmd2/transcript.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,23 @@ class is used in cmd2.py::run_transcript_tests()
1212
import re
1313
import unittest
1414
from typing import (
15+
TYPE_CHECKING,
16+
List,
17+
Optional,
1518
Tuple,
19+
cast,
1620
)
1721

1822
from . import (
1923
ansi,
2024
utils,
2125
)
2226

27+
if TYPE_CHECKING: # pragma: no cover
28+
from cmd2 import (
29+
Cmd,
30+
)
31+
2332

2433
class Cmd2TestCase(unittest.TestCase):
2534
"""A unittest class used for transcript testing.
@@ -31,7 +40,7 @@ class Cmd2TestCase(unittest.TestCase):
3140
See example.py
3241
"""
3342

34-
cmdapp = None
43+
cmdapp: Optional['Cmd'] = None
3544

3645
def setUp(self):
3746
if self.cmdapp:
@@ -54,7 +63,8 @@ def runTest(self): # was testall
5463

5564
def _fetchTranscripts(self):
5665
self.transcripts = {}
57-
for fname in self.cmdapp.testfiles:
66+
testfiles = cast(List[str], getattr(self.cmdapp, 'testfiles', []))
67+
for fname in testfiles:
5868
tfile = open(fname)
5969
self.transcripts[fname] = iter(tfile.readlines())
6070
tfile.close()

cmd2/utils.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
# coding=utf-8
22
"""Shared utility functions"""
3-
43
import argparse
54
import collections
65
import functools
@@ -17,7 +16,6 @@
1716
Enum,
1817
)
1918
from typing import (
20-
IO,
2119
TYPE_CHECKING,
2220
Any,
2321
Callable,
@@ -45,6 +43,11 @@
4543
if TYPE_CHECKING: # pragma: no cover
4644
import cmd2 # noqa: F401
4745

46+
PopenTextIO = subprocess.Popen[bytes]
47+
48+
else:
49+
PopenTextIO = subprocess.Popen
50+
4851

4952
_T = TypeVar('_T')
5053

@@ -445,7 +448,7 @@ class StdSim:
445448

446449
def __init__(
447450
self,
448-
inner_stream: Union[TextIO, 'StdSim', IO[str]],
451+
inner_stream: Union[TextIO, 'StdSim'],
449452
*,
450453
echo: bool = False,
451454
encoding: str = 'utf-8',
@@ -574,7 +577,7 @@ class ProcReader:
574577
If neither are pipes, then the process will run normally and no output will be captured.
575578
"""
576579

577-
def __init__(self, proc: subprocess.Popen, stdout: Union[StdSim, IO[str]], stderr: Union[StdSim, IO[str]]) -> None:
580+
def __init__(self, proc: PopenTextIO, stdout: Union[StdSim, TextIO], stderr: Union[StdSim, TextIO]) -> None:
578581
"""
579582
ProcReader initializer
580583
:param proc: the Popen process being read from
@@ -650,7 +653,7 @@ def _reader_thread_func(self, read_stdout: bool) -> None:
650653
# Run until process completes
651654
while self._proc.poll() is None:
652655
# noinspection PyUnresolvedReferences
653-
available = read_stream.peek()
656+
available = read_stream.peek() # type: ignore[attr-defined]
654657
if available:
655658
read_stream.read(len(available))
656659
self._write_bytes(write_stream, available)
@@ -699,8 +702,8 @@ class RedirectionSavedState:
699702

700703
def __init__(
701704
self,
702-
self_stdout: Union[StdSim, IO[str]],
703-
sys_stdout: Union[StdSim, IO[str]],
705+
self_stdout: Union[StdSim, TextIO],
706+
sys_stdout: Union[StdSim, TextIO],
704707
pipe_proc_reader: Optional[ProcReader],
705708
saved_redirecting: bool,
706709
) -> None:

0 commit comments

Comments
 (0)