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

Update type annotations #215

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
46 changes: 23 additions & 23 deletions piplicenses.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,13 @@
import subprocess
import sys
from collections import Counter
from collections.abc import Callable, Iterable, Iterator, Sequence
from enum import Enum, auto
from functools import partial
from importlib import metadata as importlib_metadata
from importlib.metadata import Distribution
from pathlib import Path
from typing import TYPE_CHECKING, Iterable, List, Type, cast
from typing import TYPE_CHECKING, cast

import tomli
from prettytable import ALL as RULE_ALL
Expand All @@ -49,9 +50,8 @@
from prettytable import NONE as RULE_NONE
from prettytable import PrettyTable

if TYPE_CHECKING:
if TYPE_CHECKING: # pragma: no cover
from email.message import Message
from typing import Callable, Dict, Iterator, Optional, Sequence


open = open # allow monkey patching
Expand Down Expand Up @@ -96,7 +96,7 @@
)


def extract_homepage(metadata: Message) -> Optional[str]:
def extract_homepage(metadata: Message) -> str | None:
"""Extracts the homepage attribute from the package metadata.

Not all python packages have defined a home-page attribute.
Expand All @@ -114,7 +114,7 @@ def extract_homepage(metadata: Message) -> Optional[str]:
if homepage is not None:
return homepage

candidates: Dict[str, str] = {}
candidates: dict[str, str] = {}

for entry in metadata.get_all("Project-URL", []):
key, value = entry.split(",", 1)
Expand Down Expand Up @@ -151,7 +151,7 @@ def normalize_pkg_name(pkg_name: str) -> str:
return PATTERN_DELIMITER.sub("-", pkg_name).lower()


METADATA_KEYS: Dict[str, List[Callable[[Message], Optional[str]]]] = {
METADATA_KEYS: dict[str, list[Callable[[Message], str | None]]] = {
"home-page": [extract_homepage],
"author": [
lambda metadata: metadata.get("author"),
Expand Down Expand Up @@ -310,7 +310,7 @@ def get_python_sys_path(executable: str) -> list[str]:

license_names = select_license_by_source(
args.from_,
cast(List[str], pkg_info["license_classifier"]),
cast(list[str], pkg_info["license_classifier"]),
cast(str, pkg_info["license"]),
)

Expand Down Expand Up @@ -372,7 +372,7 @@ def create_licenses_table(
if field == "License":
license_set = select_license_by_source(
args.from_,
cast(List[str], pkg["license_classifier"]),
cast(list[str], pkg["license_classifier"]),
cast(str, pkg["license"]),
)
license_str = "; ".join(sorted(license_set))
Expand All @@ -397,7 +397,7 @@ def create_summary_table(args: CustomNamespace) -> PrettyTable:
sorted(
select_license_by_source(
args.from_,
cast(List[str], pkg["license_classifier"]),
cast(list[str], pkg["license_classifier"]),
cast(str, pkg["license"]),
)
)
Expand Down Expand Up @@ -453,7 +453,7 @@ class JsonPrettyTable(PrettyTable):
"""PrettyTable-like class exporting to JSON"""

def _format_row(self, row: Iterable[str]) -> dict[str, str | list[str]]:
resrow: dict[str, str | List[str]] = {}
resrow: dict[str, str | list[str]] = {}
for field, value in zip(self._field_names, row):
resrow[field] = value

Expand All @@ -478,7 +478,7 @@ def get_string(self, **kwargs: str | list[str]) -> str:

class JsonLicenseFinderTable(JsonPrettyTable):
def _format_row(self, row: Iterable[str]) -> dict[str, str | list[str]]:
resrow: dict[str, str | List[str]] = {}
resrow: dict[str, str | list[str]] = {}
for field, value in zip(self._field_names, row):
if field == "Name":
resrow["name"] = value
Expand Down Expand Up @@ -734,7 +734,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 = 30
super().__init__(
Expand Down Expand Up @@ -764,7 +764,7 @@ def _expand_help(self, action: argparse.Action) -> str:
}
return super()._expand_help(action)

def _split_lines(self, text: str, width: int) -> List[str]:
def _split_lines(self, text: str, width: int) -> list[str]:
separator_pos = text[:3].find("|")
if separator_pos != -1:
flag_splitlines: bool = "R" in text[:separator_pos]
Expand All @@ -775,13 +775,13 @@ def _split_lines(self, text: str, width: int) -> List[str]:


class CustomNamespace(argparse.Namespace):
from_: "FromArg"
order: "OrderArg"
format_: "FormatArg"
from_: FromArg
order: OrderArg
format_: FormatArg
summary: bool
output_file: str
ignore_packages: List[str]
packages: List[str]
ignore_packages: list[str]
packages: list[str]
with_system: bool
with_authors: bool
with_urls: bool
Expand All @@ -792,8 +792,8 @@ class CustomNamespace(argparse.Namespace):
filter_strings: bool
filter_code_page: str
partial_match: bool
fail_on: Optional[str]
allow_only: Optional[str]
fail_on: str | None
allow_only: str | None


class CompatibleArgumentParser(argparse.ArgumentParser):
Expand Down Expand Up @@ -871,14 +871,14 @@ def enum_key_to_value(enum_key: Enum) -> str:
return enum_key.name.replace("_", "-").lower()


def choices_from_enum(enum_cls: Type[NoValueEnum]) -> List[str]:
def choices_from_enum(enum_cls: type[NoValueEnum]) -> list[str]:
return [
key.replace("_", "-").lower() for key in enum_cls.__members__.keys()
]


def get_value_from_enum(
enum_cls: Type[NoValueEnum], value: str
enum_cls: type[NoValueEnum], value: str
) -> NoValueEnum:
return getattr(enum_cls, value_to_enum_key(value))

Expand All @@ -896,7 +896,7 @@ def __call__( # type: ignore[override]
parser: argparse.ArgumentParser,
namespace: argparse.Namespace,
values: str,
option_string: Optional[str] = None,
option_string: str | None = None,
) -> None:
enum_cls = MAP_DEST_TO_ENUM[self.dest]
setattr(namespace, self.dest, get_value_from_enum(enum_cls, values))
Expand Down
4 changes: 2 additions & 2 deletions test_piplicenses.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from enum import Enum, auto
from importlib.metadata import Distribution
from types import SimpleNamespace
from typing import TYPE_CHECKING, Any, List
from typing import TYPE_CHECKING, Any
from unittest.mock import MagicMock

import docutils.frontend
Expand Down Expand Up @@ -263,7 +263,7 @@ def test_display_multiple_license_from_classifier(self) -> None:
)

def test_if_no_classifiers_then_no_licences_found(self) -> None:
classifiers: List[str] = []
classifiers: list[str] = []
self.assertEqual([], find_license_from_classifier(classifiers))

def test_select_license_by_source(self) -> None:
Expand Down