Skip to content

Use future annotations #483

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 libvcs

<!-- Maintainers, insert changes / features for the next release here -->

### Development

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

- 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/

## libvcs 0.34.0 (2024-11-22)

_Maintenance only, no bug fixes, or new features_
Expand Down
6 changes: 5 additions & 1 deletion conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,15 @@
https://docs.pytest.org/en/stable/deprecations.html
"""

import pathlib
from __future__ import annotations

import typing as t

import pytest

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 libvcs."""

from __future__ import annotations

import inspect
import pathlib
import sys
Expand Down Expand Up @@ -71,7 +73,7 @@
html_favicon = "_static/favicon.ico"
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/libvcs.svg",
"dark_logo": "img/libvcs-dark.svg",
"footer_icons": [
Expand Down Expand Up @@ -150,7 +152,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 @@ -220,14 +222,14 @@ 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:
tabs_js = pathlib.Path(app.builder.outdir) / "_static" / "tabs.js"
tabs_js.unlink(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 @@ -154,6 +154,7 @@ exclude_lines = [
"if TYPE_CHECKING:",
"if t.TYPE_CHECKING:",
"@overload( |$)",
"from __future__ import annotations",
]

[tool.ruff]
Expand All @@ -177,16 +178,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 = [
"libvcs",
]
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/libvcs/__about__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Metadata package for libvcs."""

from __future__ import annotations

__title__ = "libvcs"
__package_name__ = "libvcs"
__description__ = "Lite, typed, python utilities for Git, SVN, Mercurial, etc."
Expand Down
2 changes: 2 additions & 0 deletions src/libvcs/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Project package for libvcs."""

from __future__ import annotations

import logging

from ._internal.run import CmdLoggingAdapter
Expand Down
4 changes: 3 additions & 1 deletion src/libvcs/_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
2 changes: 2 additions & 0 deletions src/libvcs/_internal/module_loading.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import sys
import typing as t

Expand Down
74 changes: 38 additions & 36 deletions src/libvcs/_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 @@ -28,7 +30,7 @@ class ObjectDoesNotExist(Exception):
def keygetter(
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 @@ -94,7 +96,7 @@ def keygetter(
return dct


def parse_lookup(obj: Mapping[str, t.Any], path: str, lookup: str) -> t.Optional[t.Any]:
def parse_lookup(obj: Mapping[str, t.Any], path: str, lookup: str) -> 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 @@ -134,23 +136,23 @@ 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."""
...


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 @@ -159,8 +161,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 @@ -169,8 +171,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 @@ -184,8 +186,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 @@ -194,8 +196,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 @@ -204,8 +206,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 @@ -214,17 +216,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 @@ -248,8 +250,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 @@ -273,17 +275,17 @@ 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))
Expand Down Expand Up @@ -467,9 +469,9 @@ class QueryList(list[T], t.Generic[T]):
"""

data: Sequence[T]
pk_key: t.Optional[str]
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 @@ -502,9 +504,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]:
def filter_lookup(obj: t.Any) -> bool:
for path, v in kwargs.items():
try:
Expand All @@ -529,7 +531,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 @@ -542,10 +544,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:
objs = self.filter(matcher=matcher, **kwargs)
if len(objs) > 1:
raise MultipleObjectsReturned
Expand Down
Loading
Loading