Skip to content

Commit b562f3e

Browse files
committed
WIP: Typing changes left
1 parent 1e675ab commit b562f3e

File tree

8 files changed

+40
-31
lines changed

8 files changed

+40
-31
lines changed

pylint/checkers/similar.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -49,10 +49,11 @@
4949
import sys
5050
from collections import defaultdict
5151
from getopt import getopt
52-
from io import BufferedIOBase, BufferedReader, BytesIO
52+
from io import BufferedReader, BytesIO
5353
from itertools import chain, groupby
5454
from typing import (
5555
Any,
56+
Callable,
5657
Dict,
5758
FrozenSet,
5859
Generator,
@@ -379,12 +380,10 @@ def append_stream(
379380
self, streamid: str, stream: STREAM_TYPES, encoding: Optional[str] = None
380381
) -> None:
381382
"""append a file to search for similarities"""
382-
if isinstance(stream, BufferedIOBase):
383-
if encoding is None:
384-
raise ValueError
385-
readlines = decoding_stream(stream, encoding).readlines
383+
if encoding is None:
384+
readlines: Union[Callable[..., Union[str, bytes]], Any] = stream.readlines
386385
else:
387-
readlines = stream.readlines # type: ignore # hint parameter is incorrectly typed as non-optional
386+
readlines = decoding_stream(stream, encoding).readlines
388387
try:
389388
self.linesets.append(
390389
LineSet(

pylint/reporters/base_reporter.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def set_output(self, output: Optional[TextIO] = None) -> None:
4545
)
4646
self.out = output or sys.stdout
4747

48-
def writeln(self, string=""):
48+
def writeln(self, string: str = "") -> None:
4949
"""write a line in the output buffer"""
5050
print(string, file=self.out)
5151

pylint/testutils/checker_test_case.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,34 +2,37 @@
22
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
33

44
import contextlib
5-
from typing import Dict, Optional, Type
5+
from typing import Dict, Iterator, Type
6+
7+
from astroid.nodes import Module
68

79
from pylint.testutils.global_test_linter import linter
10+
from pylint.testutils.output_line import Message
811
from pylint.testutils.unittest_linter import UnittestLinter
912
from pylint.utils import ASTWalker
1013

1114

1215
class CheckerTestCase:
1316
"""A base testcase class for unit testing individual checker classes."""
1417

15-
CHECKER_CLASS: Optional[Type] = None
18+
CHECKER_CLASS: Type
1619
CONFIG: Dict = {}
1720

18-
def setup_method(self):
21+
def setup_method(self) -> None:
1922
self.linter = UnittestLinter()
2023
self.checker = self.CHECKER_CLASS(self.linter) # pylint: disable=not-callable
2124
for key, value in self.CONFIG.items():
2225
setattr(self.checker.config, key, value)
2326
self.checker.open()
2427

2528
@contextlib.contextmanager
26-
def assertNoMessages(self):
29+
def assertNoMessages(self) -> Iterator[None]:
2730
"""Assert that no messages are added by the given method."""
2831
with self.assertAddsMessages():
2932
yield
3033

3134
@contextlib.contextmanager
32-
def assertAddsMessages(self, *messages):
35+
def assertAddsMessages(self, *messages: Message) -> Iterator[None]:
3336
"""Assert that exactly the given method adds the given messages.
3437
3538
The list of messages must exactly match *all* the messages added by the
@@ -47,7 +50,7 @@ def assertAddsMessages(self, *messages):
4750
)
4851
assert got == list(messages), msg
4952

50-
def walk(self, node):
53+
def walk(self, node: Module) -> None:
5154
"""recursive walk on the given node"""
5255
walker = ASTWalker(linter)
5356
walker.add_checker(self.checker)

pylint/testutils/reporter_for_tests.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ def __init__(
2323
): # pylint: disable=super-init-not-called # See https://github.com/PyCQA/pylint/issues/4941
2424
self.reset()
2525

26-
def reset(self):
26+
def reset(self) -> None:
2727
self.message_ids: Dict = {}
2828
self.out = StringIO()
2929
self.path_strip_prefix: str = getcwd() + sep
@@ -45,11 +45,12 @@ def handle_message(self, msg: Message) -> None:
4545
str_message = str_message.replace("\r\n", "\n")
4646
self.messages.append(f"{sigle}:{line:>3}{obj}: {str_message}")
4747

48-
def finalize(self):
48+
def finalize(self) -> str:
4949
self.messages.sort()
5050
for msg in self.messages:
5151
print(msg, file=self.out)
52-
result = self.out.getvalue()
52+
if isinstance(self.out, StringIO):
53+
result = self.out.getvalue()
5354
self.reset()
5455
return result
5556

pylint/testutils/tokenize_str.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33

44
import tokenize
55
from io import StringIO
6+
from tokenize import TokenInfo
7+
from typing import List
68

79

8-
def _tokenize_str(code):
10+
def _tokenize_str(code: str) -> List[TokenInfo]:
911
return list(tokenize.generate_tokens(StringIO(code).readline))

pylint/utils/ast_walker.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,28 +3,32 @@
33

44
import collections
55
import traceback
6+
from typing import TYPE_CHECKING, Any, Callable, DefaultDict
67

78
from astroid import nodes
89

10+
if TYPE_CHECKING:
11+
from pylint.lint.pylinter import PyLinter
12+
913

1014
class ASTWalker:
11-
def __init__(self, linter):
15+
def __init__(self, linter: "PyLinter") -> None:
1216
# callbacks per node types
1317
self.nbstatements = 0
14-
self.visit_events = collections.defaultdict(list)
15-
self.leave_events = collections.defaultdict(list)
18+
self.visit_events: DefaultDict = collections.defaultdict(list)
19+
self.leave_events: DefaultDict = collections.defaultdict(list)
1620
self.linter = linter
1721
self.exception_msg = False
1822

19-
def _is_method_enabled(self, method):
23+
def _is_method_enabled(self, method: Callable) -> bool:
2024
if not hasattr(method, "checks_msgs"):
2125
return True
22-
for msg_desc in method.checks_msgs:
26+
for msg_desc in method.checks_msgs: # type: ignore # mypy does not pick up that method always has checks_msgs
2327
if self.linter.is_message_enabled(msg_desc):
2428
return True
2529
return False
2630

27-
def add_checker(self, checker):
31+
def add_checker(self, checker: Any) -> None:
2832
"""walk to the checker's dir and collect visit and leave methods"""
2933
vcids = set()
3034
lcids = set()
@@ -54,7 +58,7 @@ def add_checker(self, checker):
5458
visits[cid].append(visit_default)
5559
# for now we have no "leave_default" method in Pylint
5660

57-
def walk(self, astroid):
61+
def walk(self, astroid: Any) -> None:
5862
"""call visit events of astroid checkers for the given node, recurse on
5963
its children, then leave events.
6064
"""

pylint/utils/pragma_parser.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
import re
55
from collections import namedtuple
6-
from typing import Generator, List
6+
from typing import Generator, List, Optional
77

88
# Allow stopping after the first semicolon/hash encountered,
99
# so that an option can be continued with the reasons
@@ -52,7 +52,7 @@
5252
)
5353

5454

55-
def emit_pragma_representer(action, messages):
55+
def emit_pragma_representer(action: str, messages: List[str]) -> PragmaRepresenter:
5656
if not messages and action in MESSAGE_KEYWORDS:
5757
raise InvalidPragmaError(
5858
"The keyword is not followed by message identifier", action
@@ -65,7 +65,7 @@ class PragmaParserError(Exception):
6565
A class for exceptions thrown by pragma_parser module
6666
"""
6767

68-
def __init__(self, message, token):
68+
def __init__(self, message: str, token: str) -> None:
6969
"""
7070
:args message: explain the reason why the exception has been thrown
7171
:args token: token concerned by the exception
@@ -88,7 +88,7 @@ class InvalidPragmaError(PragmaParserError):
8888

8989

9090
def parse_pragma(pylint_pragma: str) -> Generator[PragmaRepresenter, None, None]:
91-
action = None
91+
action: Optional[str] = None
9292
messages: List[str] = []
9393
assignment_required = False
9494
previous_token = ""
@@ -112,7 +112,7 @@ def parse_pragma(pylint_pragma: str) -> Generator[PragmaRepresenter, None, None]
112112
# Nothing at all detected before this assignment
113113
raise InvalidPragmaError("Missing keyword before assignment", "")
114114
assignment_required = False
115-
elif assignment_required:
115+
elif assignment_required and action:
116116
raise InvalidPragmaError("The = sign is missing after the keyword", action)
117117
elif kind == "KEYWORD":
118118
if action:

tests/utils/unittest_ast_walker.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def test_check_messages(self) -> None:
4242
linter = self.MockLinter(
4343
{"first-message": True, "second-message": False, "third-message": True}
4444
)
45-
walker = ASTWalker(linter)
45+
walker = ASTWalker(linter) # type: ignore # Can't import MockLinter. This needs a refactor
4646
checker = self.Checker()
4747
walker.add_checker(checker)
4848
walker.walk(astroid.parse("x = func()"))
@@ -58,7 +58,7 @@ def visit_assname(self, node): # pylint: disable=unused-argument
5858
self.called = True
5959

6060
linter = self.MockLinter({"first-message": True})
61-
walker = ASTWalker(linter)
61+
walker = ASTWalker(linter) # type: ignore # Can't import MockLinter. This needs a refactor
6262
checker = Checker()
6363
walker.add_checker(checker)
6464
with warnings.catch_warnings(record=True):

0 commit comments

Comments
 (0)