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

chore: Upgrade typing semantics to Python 3.9 #273

Merged
merged 1 commit into from
Dec 11, 2024
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
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ repos:
rev: v3.19.0
hooks:
- id: pyupgrade
args: [--py37-plus, --keep-runtime-typing]
args: [--py39-plus, --keep-runtime-typing]
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: "v0.7.0"
hooks:
Expand Down
4 changes: 1 addition & 3 deletions docs/scripts/gen_command_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@
import sys
from pathlib import Path
from typing import Any
from typing import Dict
from typing import List

import yaml # type: ignore
from zabbix_cli.app import app
Expand All @@ -27,7 +25,7 @@ def main() -> None:
commands = get_app_commands(app)
command_names = [c.name for c in commands]

categories: Dict[str, List[Dict[str, Any]]] = {}
categories: dict[str, list[dict[str, Any]]] = {}
for command in commands:
category = command.category or ""
if category not in categories:
Expand Down
6 changes: 2 additions & 4 deletions docs/scripts/gen_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
import sys
from pathlib import Path
from typing import Any
from typing import Dict
from typing import List

import jinja2
import yaml # type: ignore
Expand Down Expand Up @@ -34,7 +32,7 @@ def gen_category_command_map(commands: list[CommandSummary]) -> None:
"""Generates a YAML file with all categories and detailed information
about their respective commands.
"""
categories: Dict[str, List[Dict[str, Any]]] = {}
categories: dict[str, list[dict[str, Any]]] = {}
for command in commands:
category = command.category or ""
if category not in categories:
Expand All @@ -51,7 +49,7 @@ def gen_category_pages(commands: list[CommandSummary]) -> None:
"""Renders markdown pages for each category with detailed information
about each command.
"""
categories: Dict[str, List[CommandSummary]] = {}
categories: dict[str, list[CommandSummary]] = {}
for command in commands:
if command.hidden:
continue
Expand Down
18 changes: 8 additions & 10 deletions docs/scripts/utils/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

from functools import lru_cache
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
from typing import Union
from typing import cast
Expand Down Expand Up @@ -35,7 +33,7 @@ class ParamSummary(BaseModel):

allow_from_autoenv: Optional[bool] = None
confirmation_prompt: Optional[bool] = None
choices: Optional[List[str]] = None
choices: Optional[list[str]] = None
count: Optional[bool] = None
default: Optional[Any] = None
envvar: Optional[str]
Expand All @@ -54,11 +52,11 @@ class ParamSummary(BaseModel):
multiple: bool
name: Optional[str]
nargs: int
opts: List[str]
opts: list[str]
prompt: Optional[str] = None
prompt_required: Optional[bool] = None
required: bool
secondary_opts: List[str] = []
secondary_opts: list[str] = []
show_choices: Optional[bool] = None
show_default: Optional[bool] = None
show_envvar: Optional[bool] = None
Expand Down Expand Up @@ -152,7 +150,7 @@ class CommandSummary(BaseModel):
hidden: bool
name: str
options_metavar: str
params: List[ParamSummary] = Field([], exclude=True)
params: list[ParamSummary] = Field([], exclude=True)
score: int = 0 # match score (not part of TyperCommand)
short_help: Optional[str]

Expand All @@ -162,7 +160,7 @@ def _replace_placeholders(cls, values: Any) -> Any:
"""Replace DefaultPlaceholder values with empty strings."""
if not isinstance(values, dict):
return values
values = cast(Dict[str, Any], values)
values = cast(dict[str, Any], values)
for key, value in values.items():
if isinstance(value, DefaultPlaceholder):
# Use its value, otherwise empty string
Expand Down Expand Up @@ -233,12 +231,12 @@ def usage(self) -> str:

@computed_field
@property
def options(self) -> List[ParamSummary]:
def options(self) -> list[ParamSummary]:
return [p for p in self.params if _include_opt(p)]

@computed_field
@property
def arguments(self) -> List[ParamSummary]:
def arguments(self) -> list[ParamSummary]:
return [p for p in self.params if _include_arg(p)]


Expand Down Expand Up @@ -322,7 +320,7 @@ def _get_app_commands(

def get_app_callback_options(app: typer.Typer) -> list[typer.models.OptionInfo]:
"""Get the options of the main callback of a Typer app."""
options: List[typer.models.OptionInfo] = []
options: list[typer.models.OptionInfo] = []

if not app.registered_callback:
return options
Expand Down
7 changes: 3 additions & 4 deletions docs/scripts/utils/markup.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import itertools
from dataclasses import dataclass
from functools import cmp_to_key
from typing import List

from rich.text import Text
from zabbix_cli.output.style import CodeBlockStyle
Expand Down Expand Up @@ -44,7 +43,7 @@ class MarkdownSymbol:

@property
def symbol(self) -> str:
symbol: List[str] = []
symbol: list[str] = []
if self.codeblock:
# Only insert language when opening codeblock
lang = self.language if not self.end else ""
Expand Down Expand Up @@ -102,7 +101,7 @@ def markup_to_markdown(s: str) -> str:
good enough for our purposes.
"""
t = Text.from_markup(normalize_spaces(s))
spans: List[MarkdownSpan] = []
spans: list[MarkdownSpan] = []
# Markdown has more limited styles than Rich markup, so we just
# identify the ones we care about and ignore the rest.
for span in t.spans:
Expand Down Expand Up @@ -141,7 +140,7 @@ def markup_to_markdown(s: str) -> str:
def normalize_spaces(s: str) -> str:
"""Normalizes spaces in a string while keeping newlines intact."""
split = filter(None, s.split(" "))
parts: List[str] = []
parts: list[str] = []
for part in split:
if part.endswith("\n"):
parts.append(part)
Expand Down
4 changes: 2 additions & 2 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from __future__ import annotations

from collections.abc import Generator
from collections.abc import Iterator
from pathlib import Path
from typing import Any
from typing import Generator
from typing import Iterator

import pytest
import typer
Expand Down
5 changes: 2 additions & 3 deletions tests/pyzabbix/test_client.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from __future__ import annotations

from typing import Any
from typing import Dict

import pytest
from inline_snapshot import snapshot
Expand Down Expand Up @@ -53,7 +52,7 @@
),
],
)
def test_append_param(inp: Any, key: str, value: Any, expect: Dict[str, Any]) -> None:
def test_append_param(inp: Any, key: str, value: Any, expect: dict[str, Any]) -> None:
result = append_param(inp, key, value)
assert result == expect
# Check in-place modification
Expand All @@ -71,7 +70,7 @@ def test_append_param(inp: Any, key: str, value: Any, expect: Dict[str, Any]) ->
),
],
)
def test_add_param(inp: Any, subkey: str, value: Any, expect: Dict[str, Any]) -> None:
def test_add_param(inp: Any, subkey: str, value: Any, expect: dict[str, Any]) -> None:
result = add_param(inp, "search", subkey, value)
assert result == expect
# Check in-place modification
Expand Down
4 changes: 1 addition & 3 deletions tests/pyzabbix/test_enums.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
from __future__ import annotations

from typing import Type

import pytest
from zabbix_cli.pyzabbix.enums import AckStatus
from zabbix_cli.pyzabbix.enums import ActiveInterface
Expand Down Expand Up @@ -68,7 +66,7 @@


@pytest.mark.parametrize("enum", APISTR_ENUMS)
def test_apistrenum(enum: Type[APIStrEnum]) -> None:
def test_apistrenum(enum: type[APIStrEnum]) -> None:
assert enum.__members__
members = list(enum)
assert members
Expand Down
18 changes: 6 additions & 12 deletions tests/test_config.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
from __future__ import annotations

import sys
from pathlib import Path
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
from typing import Type
from typing import Union

import pytest
Expand Down Expand Up @@ -194,15 +190,13 @@ def test_config_get_with_annotations() -> None:

# List type
assert config.get("extra4", type=list) == [1, 2, 3]
assert config.get("extra4", type=List[int]) == [1, 2, 3]
if sys.version_info >= (3, 9):
assert config.get("extra4", type=list[int]) == [1, 2, 3]
assert config.get("extra4", type=list[int]) == [1, 2, 3]
assert config.get("extra4", type=list[int]) == [1, 2, 3]

# Dict type
assert config.get("extra5", type=dict) == {"foo": [1, 2, 3]}
assert config.get("extra5", type=Dict[str, List[int]]) == {"foo": [1, 2, 3]}
if sys.version_info >= (3, 9):
assert config.get("extra5", type=dict[str, list[int]]) == {"foo": [1, 2, 3]}
assert config.get("extra5", type=dict[str, list[int]]) == {"foo": [1, 2, 3]}
assert config.get("extra5", type=dict[str, list[int]]) == {"foo": [1, 2, 3]}


def test_plugin_config_set() -> None:
Expand Down Expand Up @@ -443,9 +437,9 @@ def test_deprecated_fields_updated() -> None:
assert conf.api.username == "System-User"


def get_deprecated_fields(model: Union[Type[BaseModel], BaseModel]) -> List[str]:
def get_deprecated_fields(model: Union[type[BaseModel], BaseModel]) -> list[str]:
"""Get a set of names of deprecated fields in a model and its submodels."""
fields: List[str] = []
fields: list[str] = []
for field_name, field in model.model_fields.items():
if field.deprecated:
fields.append(field_name)
Expand Down
5 changes: 2 additions & 3 deletions tests/test_console.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import logging
from typing import Any
from typing import Dict

import pytest
from inline_snapshot import snapshot
Expand Down Expand Up @@ -39,14 +38,14 @@
),
],
)
def test_get_extra_dict(inp: Dict[str, Any], expect: Dict[str, Any]) -> None:
def test_get_extra_dict(inp: dict[str, Any], expect: dict[str, Any]) -> None:
extra = get_extra_dict(**inp)
assert extra == expect


def test_get_extra_dict_reserved_keys() -> None:
"""Test that all reserved keys are renamed."""
d: Dict[str, Any] = {}
d: dict[str, Any] = {}
for key in RESERVED_EXTRA_KEYS:
d[key] = key
extra = get_extra_dict(**d)
Expand Down
4 changes: 1 addition & 3 deletions tests/test_exceptions.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
from __future__ import annotations

from typing import Type

import pytest
from inline_snapshot import snapshot
from zabbix_cli.exceptions import ZabbixAPIException
Expand All @@ -15,7 +13,7 @@
@pytest.mark.parametrize(
"outer_t", [TypeError, ValueError, ZabbixCLIError, ZabbixAPIException]
)
def test_get_cause_args(outer_t: Type[Exception]) -> None:
def test_get_cause_args(outer_t: type[Exception]) -> None:
try:
try:
try:
Expand Down
9 changes: 4 additions & 5 deletions tests/test_models.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from __future__ import annotations

import logging
from typing import List

import pytest
from inline_snapshot import snapshot
Expand Down Expand Up @@ -45,18 +44,18 @@ class TestTableRenderable(TableRenderable):
],
)
def test_table_renderable_metakey_join_char(
content: List[str], join_char: str, expect: str
content: list[str], join_char: str, expect: str
) -> None:
class TestTableRenderable(TableRenderable):
foo: List[str] = Field(..., json_schema_extra={MetaKey.JOIN_CHAR: join_char})
foo: list[str] = Field(..., json_schema_extra={MetaKey.JOIN_CHAR: join_char})

t = TestTableRenderable(foo=content)
assert t.__rows__() == [expect]


def test_all_metakeys() -> None:
class TestTableRenderable(TableRenderable):
foo: List[str] = Field(
foo: list[str] = Field(
...,
json_schema_extra={MetaKey.JOIN_CHAR: "|", MetaKey.HEADER: "Foo Header"},
)
Expand All @@ -75,7 +74,7 @@ class FooModel(BaseModel):
foo: str
bar: int
baz: float
qux: List[str]
qux: list[str]

class TestTableRenderable(TableRenderable):
foo: FooModel
Expand Down
3 changes: 1 addition & 2 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from datetime import datetime
from datetime import timedelta
from typing import Tuple

import pytest
from freezegun import freeze_time
Expand Down Expand Up @@ -95,7 +94,7 @@ def test_convert_duration(input: str, expect: timedelta) -> None:
],
)
def test_convert_timestamp_interval(
input: str, expect: Tuple[datetime, datetime]
input: str, expect: tuple[datetime, datetime]
) -> None:
assert convert_timestamp_interval(input) == expect
# TODO: test with mix of formats. e.g. "2016-11-21T22:00 to 2016-11-21 23:00:00"
Expand Down
5 changes: 2 additions & 3 deletions zabbix_cli/_patches/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
if TYPE_CHECKING:
from types import TracebackType
from typing import Optional
from typing import Type


class BasePatcher(ABC):
Expand All @@ -27,7 +26,7 @@ def __enter__(self) -> BasePatcher:

def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_type: Optional[type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> bool:
Expand Down Expand Up @@ -70,7 +69,7 @@ def __exit__(
raise SystemExit(1)


def get_patcher(info: str) -> Type[BasePatcher]:
def get_patcher(info: str) -> type[BasePatcher]:
"""Returns a patcher for a given package."""

class Patcher(BasePatcher):
Expand Down
Loading
Loading