Skip to content

Use future annotations #555

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

Merged
merged 6 commits into from
Jan 4, 2025
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
11 changes: 11 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,17 @@ $ pip install --user --upgrade --pre libtmux

<!-- To maintainers and contributors: Please add notes for the forthcoming version above -->

### Development

#### chore: Implement PEP 563 deferred annotation resolution (#555)

- Add `from __future__ import annotations` to defer annotation resolution and reduce unnecessary runtime computations during type checking.
- Enable Ruff checks for PEP-compliant annotations:
- [non-pep585-annotation (UP006)](https://docs.astral.sh/ruff/rules/non-pep585-annotation/)
- [non-pep604-annotation (UP007)](https://docs.astral.sh/ruff/rules/non-pep604-annotation/)

For more details on PEP 563, see: https://peps.python.org/pep-0563/

## libtmux 0.40.1 (2024-12-24)

### Bug fix
Expand Down
6 changes: 5 additions & 1 deletion conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
https://docs.pytest.org/en/stable/deprecations.html
"""

import pathlib
from __future__ import annotations

import shutil
import typing as t

Expand All @@ -21,6 +22,9 @@
from libtmux.session import Session
from libtmux.window import Window

if t.TYPE_CHECKING:
import pathlib

pytest_plugins = ["pytester"]


Expand Down
10 changes: 6 additions & 4 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# flake8: NOQA: E501
"""Sphinx configuration for libtmux."""

from __future__ import annotations

import contextlib
import inspect
import pathlib
Expand Down Expand Up @@ -72,7 +74,7 @@
html_extra_path = ["manifest.json"]
html_theme = "furo"
html_theme_path: list[str] = []
html_theme_options: dict[str, t.Union[str, list[dict[str, str]]]] = {
html_theme_options: dict[str, str | list[dict[str, str]]] = {
"light_logo": "img/libtmux.svg",
"dark_logo": "img/libtmux.svg",
"footer_icons": [
Expand Down Expand Up @@ -138,7 +140,7 @@
}


def linkcode_resolve(domain: str, info: dict[str, str]) -> t.Union[None, str]:
def linkcode_resolve(domain: str, info: dict[str, str]) -> None | str:
"""
Determine the URL corresponding to Python object.

Expand Down Expand Up @@ -208,7 +210,7 @@ def linkcode_resolve(domain: str, info: dict[str, str]) -> t.Union[None, str]:
)


def remove_tabs_js(app: "Sphinx", exc: Exception) -> None:
def remove_tabs_js(app: Sphinx, exc: Exception) -> None:
"""Remove tabs.js from _static after build."""
# Fix for sphinx-inline-tabs#18
if app.builder.format == "html" and not exc:
Expand All @@ -217,6 +219,6 @@ def remove_tabs_js(app: "Sphinx", exc: Exception) -> None:
tabs_js.unlink() # When python 3.7 deprecated, use missing_ok=True


def setup(app: "Sphinx") -> None:
def setup(app: Sphinx) -> None:
"""Configure Sphinx app hooks."""
app.connect("build-finished", remove_tabs_js)
10 changes: 10 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ exclude_lines = [
"if TYPE_CHECKING:",
"if t.TYPE_CHECKING:",
"@overload( |$)",
"from __future__ import annotations",
]

[tool.ruff]
Expand All @@ -168,16 +169,25 @@ select = [
"PERF", # Perflint
"RUF", # Ruff-specific rules
"D", # pydocstyle
"FA100", # future annotations
]
ignore = [
"COM812", # missing trailing comma, ruff format conflict
]
extend-safe-fixes = [
"UP006",
"UP007",
]
pyupgrade.keep-runtime-typing = false

[tool.ruff.lint.isort]
known-first-party = [
"libtmux",
]
combine-as-imports = true
required-imports = [
"from __future__ import annotations",
]

[tool.ruff.lint.pydocstyle]
convention = "numpy"
Expand Down
2 changes: 2 additions & 0 deletions src/libtmux/__about__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Metadata package for libtmux."""

from __future__ import annotations

__title__ = "libtmux"
__package_name__ = "libtmux"
__version__ = "0.40.1"
Expand Down
2 changes: 2 additions & 0 deletions src/libtmux/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""libtmux, a typed, pythonic API wrapper for the tmux terminal multiplexer."""

from __future__ import annotations

from .__about__ import (
__author__,
__copyright__,
Expand Down
4 changes: 3 additions & 1 deletion src/libtmux/_internal/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
This is an internal API not covered by versioning policy.
"""

from __future__ import annotations

import dataclasses
import typing as t
from operator import attrgetter
Expand Down Expand Up @@ -78,7 +80,7 @@ class SkipDefaultFieldsReprMixin:
ItemWithMixin(name=Test, unit_price=2.05)
"""

def __repr__(self: "DataclassInstance") -> str:
def __repr__(self: DataclassInstance) -> str:
"""Omit default fields in object representation."""
nodef_f_vals = (
(f.name, attrgetter(f.name)(self))
Expand Down
82 changes: 42 additions & 40 deletions src/libtmux/_internal/query_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
This is an internal API not covered by versioning policy.
"""

from __future__ import annotations

import logging
import re
import traceback
Expand All @@ -20,8 +22,8 @@ class LookupProtocol(t.Protocol):

def __call__(
self,
data: t.Union[str, list[str], "Mapping[str, str]"],
rhs: t.Union[str, list[str], "Mapping[str, str]", "re.Pattern[str]"],
data: str | list[str] | Mapping[str, str],
rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
) -> bool:
"""Return callback for :class:`QueryList` filtering operators."""
...
Expand All @@ -41,9 +43,9 @@ class ObjectDoesNotExist(Exception):


def keygetter(
obj: "Mapping[str, t.Any]",
obj: Mapping[str, t.Any],
path: str,
) -> t.Union[None, t.Any, str, list[str], "Mapping[str, str]"]:
) -> None | t.Any | str | list[str] | Mapping[str, str]:
"""Fetch values in objects and keys, supported nested data.

**With dictionaries**:
Expand Down Expand Up @@ -112,10 +114,10 @@ def keygetter(


def parse_lookup(
obj: "Mapping[str, t.Any]",
obj: Mapping[str, t.Any],
path: str,
lookup: str,
) -> t.Optional[t.Any]:
) -> t.Any | None:
"""Check if field lookup key, e.g. "my__path__contains" has comparator, return val.

If comparator not used or value not found, return None.
Expand Down Expand Up @@ -151,15 +153,15 @@ def parse_lookup(


def lookup_exact(
data: t.Union[str, list[str], "Mapping[str, str]"],
rhs: t.Union[str, list[str], "Mapping[str, str]", "re.Pattern[str]"],
data: str | list[str] | Mapping[str, str],
rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
) -> bool:
return rhs == data


def lookup_iexact(
data: t.Union[str, list[str], "Mapping[str, str]"],
rhs: t.Union[str, list[str], "Mapping[str, str]", "re.Pattern[str]"],
data: str | list[str] | Mapping[str, str],
rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
) -> bool:
if not isinstance(rhs, str) or not isinstance(data, str):
return False
Expand All @@ -168,8 +170,8 @@ def lookup_iexact(


def lookup_contains(
data: t.Union[str, list[str], "Mapping[str, str]"],
rhs: t.Union[str, list[str], "Mapping[str, str]", "re.Pattern[str]"],
data: str | list[str] | Mapping[str, str],
rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
) -> bool:
if not isinstance(rhs, str) or not isinstance(data, (str, Mapping, list)):
return False
Expand All @@ -178,8 +180,8 @@ def lookup_contains(


def lookup_icontains(
data: t.Union[str, list[str], "Mapping[str, str]"],
rhs: t.Union[str, list[str], "Mapping[str, str]", "re.Pattern[str]"],
data: str | list[str] | Mapping[str, str],
rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
) -> bool:
if not isinstance(rhs, str) or not isinstance(data, (str, Mapping, list)):
return False
Expand All @@ -193,8 +195,8 @@ def lookup_icontains(


def lookup_startswith(
data: t.Union[str, list[str], "Mapping[str, str]"],
rhs: t.Union[str, list[str], "Mapping[str, str]", "re.Pattern[str]"],
data: str | list[str] | Mapping[str, str],
rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
) -> bool:
if not isinstance(rhs, str) or not isinstance(data, str):
return False
Expand All @@ -203,8 +205,8 @@ def lookup_startswith(


def lookup_istartswith(
data: t.Union[str, list[str], "Mapping[str, str]"],
rhs: t.Union[str, list[str], "Mapping[str, str]", "re.Pattern[str]"],
data: str | list[str] | Mapping[str, str],
rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
) -> bool:
if not isinstance(rhs, str) or not isinstance(data, str):
return False
Expand All @@ -213,8 +215,8 @@ def lookup_istartswith(


def lookup_endswith(
data: t.Union[str, list[str], "Mapping[str, str]"],
rhs: t.Union[str, list[str], "Mapping[str, str]", "re.Pattern[str]"],
data: str | list[str] | Mapping[str, str],
rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
) -> bool:
if not isinstance(rhs, str) or not isinstance(data, str):
return False
Expand All @@ -223,17 +225,17 @@ def lookup_endswith(


def lookup_iendswith(
data: t.Union[str, list[str], "Mapping[str, str]"],
rhs: t.Union[str, list[str], "Mapping[str, str]", "re.Pattern[str]"],
data: str | list[str] | Mapping[str, str],
rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
) -> bool:
if not isinstance(rhs, str) or not isinstance(data, str):
return False
return data.lower().endswith(rhs.lower())


def lookup_in(
data: t.Union[str, list[str], "Mapping[str, str]"],
rhs: t.Union[str, list[str], "Mapping[str, str]", "re.Pattern[str]"],
data: str | list[str] | Mapping[str, str],
rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
) -> bool:
if isinstance(rhs, list):
return data in rhs
Expand All @@ -254,8 +256,8 @@ def lookup_in(


def lookup_nin(
data: t.Union[str, list[str], "Mapping[str, str]"],
rhs: t.Union[str, list[str], "Mapping[str, str]", "re.Pattern[str]"],
data: str | list[str] | Mapping[str, str],
rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
) -> bool:
if isinstance(rhs, list):
return data not in rhs
Expand All @@ -276,24 +278,24 @@ def lookup_nin(


def lookup_regex(
data: t.Union[str, list[str], "Mapping[str, str]"],
rhs: t.Union[str, list[str], "Mapping[str, str]", "re.Pattern[str]"],
data: str | list[str] | Mapping[str, str],
rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
) -> bool:
if isinstance(data, (str, bytes, re.Pattern)) and isinstance(rhs, (str, bytes)):
return bool(re.search(rhs, data))
return False


def lookup_iregex(
data: t.Union[str, list[str], "Mapping[str, str]"],
rhs: t.Union[str, list[str], "Mapping[str, str]", "re.Pattern[str]"],
data: str | list[str] | Mapping[str, str],
rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
) -> bool:
if isinstance(data, (str, bytes, re.Pattern)) and isinstance(rhs, (str, bytes)):
return bool(re.search(rhs, data, re.IGNORECASE))
return False


LOOKUP_NAME_MAP: 'Mapping[str, "LookupProtocol"]' = {
LOOKUP_NAME_MAP: Mapping[str, LookupProtocol] = {
"eq": lookup_exact,
"exact": lookup_exact,
"iexact": lookup_iexact,
Expand Down Expand Up @@ -469,10 +471,10 @@ class QueryList(list[T], t.Generic[T]):
[]
"""

data: "Sequence[T]"
pk_key: t.Optional[str]
data: Sequence[T]
pk_key: str | None

def __init__(self, items: t.Optional["Iterable[T]"] = None) -> None:
def __init__(self, items: Iterable[T] | None = None) -> None:
super().__init__(items if items is not None else [])

def items(self) -> list[tuple[str, T]]:
Expand Down Expand Up @@ -505,9 +507,9 @@ def __eq__(

def filter(
self,
matcher: t.Optional[t.Union[Callable[[T], bool], T]] = None,
matcher: Callable[[T], bool] | T | None = None,
**kwargs: t.Any,
) -> "QueryList[T]":
) -> QueryList[T]:
"""Filter list of objects."""

def filter_lookup(obj: t.Any) -> bool:
Expand All @@ -534,7 +536,7 @@ def filter_lookup(obj: t.Any) -> bool:
filter_ = matcher
elif matcher is not None:

def val_match(obj: t.Union[str, list[t.Any], T]) -> bool:
def val_match(obj: str | list[t.Any] | T) -> bool:
if isinstance(matcher, list):
return obj in matcher
return bool(obj == matcher)
Expand All @@ -547,10 +549,10 @@ def val_match(obj: t.Union[str, list[t.Any], T]) -> bool:

def get(
self,
matcher: t.Optional[t.Union[Callable[[T], bool], T]] = None,
default: t.Optional[t.Any] = no_arg,
matcher: Callable[[T], bool] | T | None = None,
default: t.Any | None = no_arg,
**kwargs: t.Any,
) -> t.Optional[T]:
) -> T | None:
"""Retrieve one object.

Raises :exc:`MultipleObjectsReturned` if multiple objects found.
Expand Down
3 changes: 2 additions & 1 deletion src/libtmux/_vendor/_structures.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import annotations


class InfinityType:
Expand All @@ -26,7 +27,7 @@ def __gt__(self, other: object) -> bool:
def __ge__(self, other: object) -> bool:
return True

def __neg__(self: object) -> "NegativeInfinityType":
def __neg__(self: object) -> NegativeInfinityType:
return NegativeInfinity


Expand Down
Loading
Loading