Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use python-typing-update on pylint/pyreverse directory #6309

Merged
merged 1 commit into from
Apr 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 12 additions & 13 deletions pylint/message/message.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 collections
from typing import Optional, Tuple, Union, overload
from typing import overload
from warnings import warn

from pylint.constants import MSG_TYPES
Expand Down Expand Up @@ -41,33 +43,30 @@ def __new__(
symbol: str,
location: MessageLocationTuple,
msg: str,
confidence: Optional[Confidence],
) -> "Message":
confidence: Confidence | None,
) -> Message:
...

@overload
def __new__(
cls,
msg_id: str,
symbol: str,
location: Tuple[str, str, str, str, int, int],
location: tuple[str, str, str, str, int, int],
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
location: tuple[str, str, str, str, int, int],
location: MessageLocationTuple,

(🤞 ?)

msg: str,
confidence: Optional[Confidence],
) -> "Message":
confidence: Confidence | None,
) -> Message:
# Remove for pylint 3.0
...

def __new__(
cls,
msg_id: str,
symbol: str,
location: Union[
Tuple[str, str, str, str, int, int],
MessageLocationTuple,
],
location: (tuple[str, str, str, str, int, int] | MessageLocationTuple),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
location: (tuple[str, str, str, str, int, int] | MessageLocationTuple),
location: MessageLocationTuple,

Could we do this ? It seems those should be the same thing.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, see the deprecation warning a couple of lines below. location needs to be initialised as MessageLocationTuple and not be a regular tuple.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The brackets could have been removed here though.

-    location: (tuple[str, str, str, str, int, int] | MessageLocationTuple),
+    location: tuple[str, str, str, str, int, int] | MessageLocationTuple,

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in follow-up!

msg: str,
confidence: Optional[Confidence],
) -> "Message":
confidence: Confidence | None,
) -> Message:
if not isinstance(location, MessageLocationTuple):
warn(
"In pylint 3.0, Messages will only accept a MessageLocationTuple as location parameter",
Expand All @@ -82,7 +81,7 @@ def __new__(
msg_id[0],
MSG_TYPES[msg_id[0]],
confidence,
*location
*location,
)

def format(self, template: str) -> str:
Expand Down
6 changes: 4 additions & 2 deletions pylint/pyreverse/diadefslib.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

"""Handle diagram generation options for class diagram or default diagrams."""

from typing import Any, Optional
from __future__ import annotations

from typing import Any

import astroid
from astroid import nodes
Expand Down Expand Up @@ -126,7 +128,7 @@ def visit_project(self, node: Project) -> None:
"""
mode = self.config.mode
if len(node.modules) > 1:
self.pkgdiagram: Optional[PackageDiagram] = PackageDiagram(
self.pkgdiagram: PackageDiagram | None = PackageDiagram(
f"packages {node.name}", mode
)
else:
Expand Down
24 changes: 13 additions & 11 deletions pylint/pyreverse/dot_printer.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,27 @@
# Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt

"""Class to generate files in dot format and image formats supported by Graphviz."""

from __future__ import annotations

import os
import subprocess
import sys
import tempfile
from pathlib import Path
from typing import Dict, FrozenSet, List, Optional

from astroid import nodes

from pylint.pyreverse.printer import EdgeType, Layout, NodeProperties, NodeType, Printer
from pylint.pyreverse.utils import get_annotation_label

ALLOWED_CHARSETS: FrozenSet[str] = frozenset(("utf-8", "iso-8859-1", "latin1"))
SHAPES: Dict[NodeType, str] = {
ALLOWED_CHARSETS: frozenset[str] = frozenset(("utf-8", "iso-8859-1", "latin1"))
SHAPES: dict[NodeType, str] = {
NodeType.PACKAGE: "box",
NodeType.INTERFACE: "record",
NodeType.CLASS: "record",
}
ARROWS: Dict[EdgeType, Dict[str, str]] = {
ARROWS: dict[EdgeType, dict[str, str]] = {
EdgeType.INHERITS: dict(arrowtail="none", arrowhead="empty"),
EdgeType.IMPLEMENTS: dict(arrowtail="node", arrowhead="empty", style="dashed"),
EdgeType.ASSOCIATION: dict(
Expand All @@ -37,8 +39,8 @@ class DotPrinter(Printer):
def __init__(
self,
title: str,
layout: Optional[Layout] = None,
use_automatic_namespace: Optional[bool] = None,
layout: Layout | None = None,
use_automatic_namespace: bool | None = None,
):
layout = layout or Layout.BOTTOM_TO_TOP
self.charset = "utf-8"
Expand All @@ -59,7 +61,7 @@ def emit_node(
self,
name: str,
type_: NodeType,
properties: Optional[NodeProperties] = None,
properties: NodeProperties | None = None,
) -> None:
"""Create a new node.

Expand All @@ -80,7 +82,7 @@ def emit_node(
)

def _build_label_for_node(
self, properties: NodeProperties, is_interface: Optional[bool] = False
self, properties: NodeProperties, is_interface: bool | None = False
) -> str:
if not properties.label:
return ""
Expand All @@ -95,11 +97,11 @@ def _build_label_for_node(
return label

# Add class attributes
attrs: List[str] = properties.attrs or []
attrs: list[str] = properties.attrs or []
label = "{" + label + "|" + r"\l".join(attrs) + r"\l|"

# Add class methods
methods: List[nodes.FunctionDef] = properties.methods or []
methods: list[nodes.FunctionDef] = properties.methods or []
for func in methods:
args = self._get_method_arguments(func)
label += rf"{func.name}({', '.join(args)})"
Expand All @@ -114,7 +116,7 @@ def emit_edge(
from_node: str,
to_node: str,
type_: EdgeType,
label: Optional[str] = None,
label: str | None = None,
) -> None:
"""Create an edge from one node to another to display relationships."""
arrowstyle = ARROWS[type_]
Expand Down
11 changes: 6 additions & 5 deletions pylint/pyreverse/mermaidjs_printer.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
# Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt

"""Class to generate files in mermaidjs format."""
from typing import Dict, Optional

from __future__ import annotations

from pylint.pyreverse.printer import EdgeType, NodeProperties, NodeType, Printer
from pylint.pyreverse.utils import get_annotation_label
Expand All @@ -14,12 +15,12 @@ class MermaidJSPrinter(Printer):

DEFAULT_COLOR = "black"

NODES: Dict[NodeType, str] = {
NODES: dict[NodeType, str] = {
NodeType.CLASS: "class",
NodeType.INTERFACE: "class",
NodeType.PACKAGE: "class",
}
ARROWS: Dict[EdgeType, str] = {
ARROWS: dict[EdgeType, str] = {
EdgeType.INHERITS: "--|>",
EdgeType.IMPLEMENTS: "..|>",
EdgeType.ASSOCIATION: "--*",
Expand All @@ -35,7 +36,7 @@ def emit_node(
self,
name: str,
type_: NodeType,
properties: Optional[NodeProperties] = None,
properties: NodeProperties | None = None,
) -> None:
"""Create a new node.

Expand Down Expand Up @@ -68,7 +69,7 @@ def emit_edge(
from_node: str,
to_node: str,
type_: EdgeType,
label: Optional[str] = None,
label: str | None = None,
) -> None:
"""Create an edge from one node to another to display relationships."""
from_node = from_node.split(".")[-1]
Expand Down
11 changes: 6 additions & 5 deletions pylint/pyreverse/plantuml_printer.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
# Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt

"""Class to generate files in dot format and image formats supported by Graphviz."""
from typing import Dict, Optional

from __future__ import annotations

from pylint.pyreverse.printer import EdgeType, Layout, NodeProperties, NodeType, Printer
from pylint.pyreverse.utils import get_annotation_label
Expand All @@ -14,12 +15,12 @@ class PlantUmlPrinter(Printer):

DEFAULT_COLOR = "black"

NODES: Dict[NodeType, str] = {
NODES: dict[NodeType, str] = {
NodeType.CLASS: "class",
NodeType.INTERFACE: "class",
NodeType.PACKAGE: "package",
}
ARROWS: Dict[EdgeType, str] = {
ARROWS: dict[EdgeType, str] = {
EdgeType.INHERITS: "--|>",
EdgeType.IMPLEMENTS: "..|>",
EdgeType.ASSOCIATION: "--*",
Expand All @@ -45,7 +46,7 @@ def emit_node(
self,
name: str,
type_: NodeType,
properties: Optional[NodeProperties] = None,
properties: NodeProperties | None = None,
) -> None:
"""Create a new node.

Expand Down Expand Up @@ -84,7 +85,7 @@ def emit_edge(
from_node: str,
to_node: str,
type_: EdgeType,
label: Optional[str] = None,
label: str | None = None,
) -> None:
"""Create an edge from one node to another to display relationships."""
edge = f"{from_node} {self.ARROWS[type_]} {to_node}"
Expand Down
29 changes: 16 additions & 13 deletions pylint/pyreverse/printer.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@
# Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt

"""Base class defining the interface for a printer."""

from __future__ import annotations

from abc import ABC, abstractmethod
from enum import Enum
from typing import List, NamedTuple, Optional
from typing import NamedTuple

from astroid import nodes

Expand Down Expand Up @@ -34,10 +37,10 @@ class Layout(Enum):

class NodeProperties(NamedTuple):
label: str
attrs: Optional[List[str]] = None
methods: Optional[List[nodes.FunctionDef]] = None
color: Optional[str] = None
fontcolor: Optional[str] = None
attrs: list[str] | None = None
methods: list[nodes.FunctionDef] | None = None
color: str | None = None
fontcolor: str | None = None


class Printer(ABC):
Expand All @@ -46,13 +49,13 @@ class Printer(ABC):
def __init__(
self,
title: str,
layout: Optional[Layout] = None,
use_automatic_namespace: Optional[bool] = None,
layout: Layout | None = None,
use_automatic_namespace: bool | None = None,
) -> None:
self.title: str = title
self.layout = layout
self.use_automatic_namespace = use_automatic_namespace
self.lines: List[str] = []
self.lines: list[str] = []
self._indent = ""
self._open_graph()

Expand All @@ -68,7 +71,7 @@ def _dec_indent(self) -> None:
def _open_graph(self) -> None:
"""Emit the header lines, i.e. all boilerplate code that defines things like layout etc."""

def emit(self, line: str, force_newline: Optional[bool] = True) -> None:
def emit(self, line: str, force_newline: bool | None = True) -> None:
if force_newline and not line.endswith("\n"):
line += "\n"
self.lines.append(self._indent + line)
Expand All @@ -78,7 +81,7 @@ def emit_node(
self,
name: str,
type_: NodeType,
properties: Optional[NodeProperties] = None,
properties: NodeProperties | None = None,
) -> None:
"""Create a new node.

Expand All @@ -91,17 +94,17 @@ def emit_edge(
from_node: str,
to_node: str,
type_: EdgeType,
label: Optional[str] = None,
label: str | None = None,
) -> None:
"""Create an edge from one node to another to display relationships."""

@staticmethod
def _get_method_arguments(method: nodes.FunctionDef) -> List[str]:
def _get_method_arguments(method: nodes.FunctionDef) -> list[str]:
if method.args.args is None:
return []

first_arg = 0 if method.type in {"function", "staticmethod"} else 1
arguments: List[nodes.AssignName] = method.args.args[first_arg:]
arguments: list[nodes.AssignName] = method.args.args[first_arg:]

annotations = dict(zip(arguments, method.args.annotations[first_arg:]))
for arg in arguments:
Expand Down
6 changes: 3 additions & 3 deletions pylint/pyreverse/printer_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
# Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt

from typing import Dict, Type
from __future__ import annotations

from pylint.pyreverse.dot_printer import DotPrinter
from pylint.pyreverse.mermaidjs_printer import HTMLMermaidJSPrinter, MermaidJSPrinter
from pylint.pyreverse.plantuml_printer import PlantUmlPrinter
from pylint.pyreverse.printer import Printer
from pylint.pyreverse.vcg_printer import VCGPrinter

filetype_to_printer: Dict[str, Type[Printer]] = {
filetype_to_printer: dict[str, type[Printer]] = {
"vcg": VCGPrinter,
"plantuml": PlantUmlPrinter,
"puml": PlantUmlPrinter,
Expand All @@ -20,5 +20,5 @@
}


def get_printer_for_filetype(filetype: str) -> Type[Printer]:
def get_printer_for_filetype(filetype: str) -> type[Printer]:
return filetype_to_printer.get(filetype, DotPrinter)
Loading