Skip to content

Commit

Permalink
Add some manual typing changes (#6325)
Browse files Browse the repository at this point in the history
Co-authored-by: Marc Mueller <30130371+cdce8p@users.noreply.github.com>
  • Loading branch information
DanielNoord and cdce8p committed Apr 14, 2022
1 parent a693ea7 commit 2e0a4e7
Show file tree
Hide file tree
Showing 14 changed files with 45 additions and 41 deletions.
13 changes: 7 additions & 6 deletions examples/deprecation_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,10 @@ def mymethod(self, arg0, arg1, deprecated1=None, arg2='foo', deprecated2='bar',
------------------------------------------------------------------
Your code has been rated at 2.00/10 (previous run: 2.00/10, +0.00)
"""
from typing import TYPE_CHECKING, Set, Tuple, Union

from __future__ import annotations

from typing import TYPE_CHECKING

from pylint.checkers import BaseChecker, DeprecatedMixin
from pylint.interfaces import IAstroidChecker
Expand All @@ -58,17 +61,15 @@ class DeprecationChecker(DeprecatedMixin, BaseChecker):
# The name defines a custom section of the config for this checker.
name = "deprecated"

def deprecated_methods(self) -> Set[str]:
def deprecated_methods(self) -> set[str]:
"""Callback method called by DeprecatedMixin for every method/function found in the code.
Returns:
collections.abc.Container of deprecated function/method names.
"""
return {"mymodule.deprecated_function", "mymodule.MyClass.deprecated_method"}

def deprecated_arguments(
self, method: str
) -> Tuple[Tuple[Union[int, None], str], ...]:
def deprecated_arguments(self, method: str) -> tuple[tuple[int | None, str], ...]:
"""Callback returning the deprecated arguments of method/function.
Returns:
Expand All @@ -92,5 +93,5 @@ def deprecated_arguments(
return ()


def register(linter: "PyLinter") -> None:
def register(linter: PyLinter) -> None:
linter.register_checker(DeprecationChecker(linter))
4 changes: 3 additions & 1 deletion pylint/checkers/base/name_checker/naming_style.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
# Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt

from __future__ import annotations

import re
from typing import Pattern
from re import Pattern

from pylint import constants

Expand Down
9 changes: 5 additions & 4 deletions pylint/checkers/variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,11 @@
import os
import re
import sys
from collections import defaultdict
from collections.abc import Iterable, Iterator
from enum import Enum
from functools import lru_cache
from typing import TYPE_CHECKING, Any, DefaultDict, NamedTuple
from typing import TYPE_CHECKING, Any, NamedTuple

import astroid
from astroid import nodes
Expand Down Expand Up @@ -516,7 +517,7 @@ class ScopeConsumer(NamedTuple):

to_consume: dict[str, list[nodes.NodeNG]]
consumed: dict[str, list[nodes.NodeNG]]
consumed_uncertain: DefaultDict[str, list[nodes.NodeNG]]
consumed_uncertain: defaultdict[str, list[nodes.NodeNG]]
scope_type: str


Expand Down Expand Up @@ -557,7 +558,7 @@ def consumed(self):
return self._atomic.consumed

@property
def consumed_uncertain(self) -> DefaultDict[str, list[nodes.NodeNG]]:
def consumed_uncertain(self) -> defaultdict[str, list[nodes.NodeNG]]:
"""Retrieves nodes filtered out by get_next_to_consume() that may not
have executed, such as statements in except blocks, or statements
Expand Down Expand Up @@ -2698,7 +2699,7 @@ def _check_globals(self, not_consumed):
def _check_imports(self, not_consumed):
local_names = _fix_dot_imports(not_consumed)
checked = set()
unused_wildcard_imports: DefaultDict[
unused_wildcard_imports: defaultdict[
tuple[str, nodes.ImportFrom], list[str]
] = collections.defaultdict(list)
for name, stmt in local_names:
Expand Down
5 changes: 3 additions & 2 deletions pylint/lint/parallel.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@
import collections
import functools
import warnings
from collections import defaultdict
from collections.abc import Iterable, Sequence
from typing import TYPE_CHECKING, Any, DefaultDict
from typing import TYPE_CHECKING, Any

import dill

Expand Down Expand Up @@ -66,7 +67,7 @@ def _worker_initialize(
def _worker_check_single_file(
file_item: FileItem,
) -> tuple[
int, Any, str, Any, list[tuple[Any, ...]], LinterStats, Any, DefaultDict[Any, list]
int, Any, str, Any, list[tuple[Any, ...]], LinterStats, Any, defaultdict[Any, list]
]:
if not _worker_linter:
raise Exception("Worker linter not yet initialised")
Expand Down
5 changes: 3 additions & 2 deletions pylint/lint/pylinter.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@
import tokenize
import traceback
import warnings
from collections import defaultdict
from collections.abc import Iterable, Iterator, Sequence
from io import TextIOWrapper
from typing import Any, DefaultDict
from typing import Any

import astroid
from astroid import AstroidError, nodes
Expand Down Expand Up @@ -600,7 +601,7 @@ def __init__(
"""Dictionary of possible but non-initialized reporters."""

# Attributes for checkers and plugins
self._checkers: DefaultDict[
self._checkers: defaultdict[
str, list[checkers.BaseChecker]
] = collections.defaultdict(list)
"""Dictionary of registered and initialized checkers."""
Expand Down
4 changes: 2 additions & 2 deletions pylint/lint/report_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from __future__ import annotations

import collections
from typing import DefaultDict
from collections import defaultdict

from pylint import checkers, exceptions
from pylint.reporters.ureports.nodes import Table
Expand Down Expand Up @@ -52,7 +52,7 @@ def report_messages_by_module_stats(
if len(module_stats) == 1:
# don't print this report when we are analysing a single module
raise exceptions.EmptyReportError()
by_mod: DefaultDict[str, dict[str, int | float]] = collections.defaultdict(dict)
by_mod: defaultdict[str, dict[str, int | float]] = collections.defaultdict(dict)
for m_type in ("fatal", "error", "warning", "refactor", "convention"):
total = stats.get_global_message_count(m_type)
for module in module_stats.keys():
Expand Down
2 changes: 1 addition & 1 deletion pylint/testutils/functional/test_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@

import configparser
import sys
from collections.abc import Callable
from os.path import basename, exists, join
from typing import Callable


def parse_python_version(ver_str: str) -> tuple[int, ...]:
Expand Down
3 changes: 2 additions & 1 deletion pylint/testutils/output_line.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
from __future__ import annotations

import warnings
from typing import Any, NamedTuple, Sequence, TypeVar
from collections.abc import Sequence
from typing import Any, NamedTuple, TypeVar

from astroid import nodes

Expand Down
6 changes: 4 additions & 2 deletions pylint/utils/file_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@

import collections
import sys
from typing import TYPE_CHECKING, DefaultDict, Dict, Iterator
from collections import defaultdict
from collections.abc import Iterator
from typing import TYPE_CHECKING, Dict

from astroid import nodes

Expand Down Expand Up @@ -35,7 +37,7 @@ def __init__(self, modname: str | None = None) -> None:
self.base_name = modname
self._module_msgs_state: MessageStateDict = {}
self._raw_module_msgs_state: MessageStateDict = {}
self._ignored_msgs: DefaultDict[
self._ignored_msgs: defaultdict[
tuple[str, int], set[int]
] = collections.defaultdict(set)
self._suppression_mapping: dict[tuple[str, int], int] = {}
Expand Down
2 changes: 1 addition & 1 deletion pylint/utils/pragma_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

import re
from collections import namedtuple
from typing import Generator
from collections.abc import Generator

# Allow stopping after the first semicolon/hash encountered,
# so that an option can be continued with the reasons
Expand Down
13 changes: 2 additions & 11 deletions pylint/utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,9 @@
import textwrap
import tokenize
import warnings
from collections.abc import Sequence
from io import BufferedReader, BytesIO
from typing import (
TYPE_CHECKING,
List,
Pattern,
Sequence,
TextIO,
Tuple,
TypeVar,
Union,
overload,
)
from typing import TYPE_CHECKING, List, Pattern, TextIO, Tuple, TypeVar, Union, overload

from astroid import Module, modutils, nodes

Expand Down
6 changes: 4 additions & 2 deletions script/bump_changelog.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@

"""This script permits to upgrade the changelog in astroid or pylint when releasing a version."""
# pylint: disable=logging-fstring-interpolation

from __future__ import annotations

import argparse
import enum
import logging
from datetime import datetime
from pathlib import Path
from typing import List

DEFAULT_CHANGELOG_PATH = Path("ChangeLog")

Expand Down Expand Up @@ -59,7 +61,7 @@ def get_next_version(version: str, version_type: VersionType) -> str:
return ".".join(new_version)


def get_next_versions(version: str, version_type: VersionType) -> List[str]:
def get_next_versions(version: str, version_type: VersionType) -> list[str]:

if version_type == VersionType.PATCH:
# "2.6.1" => ["2.6.2"]
Expand Down
8 changes: 5 additions & 3 deletions script/fix_documentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
# Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt

"""Small script to fix various issues with the documentation. Used by pre-commit."""

from __future__ import annotations

import argparse
import re
import sys
from typing import List, Optional, Union

INVALID_CODE_BLOCK_PATTERN = (
r"(?<=\s`)([\w\-\.\(\)\=]+\s{0,1}[\w\-\.\(\)\=]*)(?=`[,\.]{0,1}\s|$)"
Expand Down Expand Up @@ -50,7 +52,7 @@ def __init__(
prog: str,
indent_increment: int = 2,
max_help_position: int = 24,
width: Optional[int] = None,
width: int | None = None,
) -> None:
max_help_position = 40
super().__init__(
Expand All @@ -61,7 +63,7 @@ def __init__(
)


def main(argv: Union[List[str], None] = None) -> int:
def main(argv: list[str] | None = None) -> int:
argv = argv or sys.argv[1:]
parser = argparse.ArgumentParser(formatter_class=CustomHelpFormatter)
parser.add_argument(
Expand Down
6 changes: 3 additions & 3 deletions script/get_unused_message_id_category.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,22 @@
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
# Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt

from typing import List
from __future__ import annotations

from pylint.checkers import initialize as initialize_checkers
from pylint.constants import DELETED_MSGID_PREFIXES
from pylint.extensions import initialize as initialize_extensions
from pylint.lint.pylinter import PyLinter


def register_all_checkers_and_plugins(linter: "PyLinter") -> None:
def register_all_checkers_and_plugins(linter: PyLinter) -> None:
"""Registers all checkers and plugins."""
linter.cmdline_parser.set_conflict_handler("resolve")
initialize_checkers(linter)
initialize_extensions(linter)


def get_next_code_category(message_ids: List[str]) -> int:
def get_next_code_category(message_ids: list[str]) -> int:
categories = sorted({int(i[:2]) for i in message_ids})
# We add the prefixes for deleted checkers
categories += DELETED_MSGID_PREFIXES
Expand Down

0 comments on commit 2e0a4e7

Please sign in to comment.