Skip to content

Commit

Permalink
Handle qualifier wrapped with ClassVar (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
antonagestam authored Jun 7, 2022
1 parent 1590689 commit bf569ca
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 14 deletions.
12 changes: 6 additions & 6 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ default_language_version:
python: python3.10
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: "v4.1.0"
rev: "v4.3.0"
hooks:
- id: check-case-conflict
- id: check-merge-conflict
Expand All @@ -11,7 +11,7 @@ repos:
- id: debug-statements
- id: detect-private-key
- repo: https://github.com/asottile/pyupgrade
rev: "v2.31.1"
rev: "v2.34.0"
hooks:
- id: pyupgrade
args:
Expand All @@ -29,7 +29,7 @@ repos:
hooks:
- id: isort
- repo: https://github.com/psf/black
rev: "22.1.0"
rev: "22.3.0"
hooks:
- id: black
- repo: https://github.com/asottile/blacken-docs
Expand All @@ -46,11 +46,11 @@ repos:
- flake8-comprehensions
- flake8-tidy-imports
- repo: https://github.com/sirosen/check-jsonschema
rev: "0.14.0"
rev: "0.16.0"
hooks:
- id: check-github-workflows
- repo: https://github.com/pre-commit/mirrors-mypy
rev: "v0.941"
rev: "v0.961"
hooks:
- id: mypy
args: []
Expand All @@ -63,7 +63,7 @@ repos:
- id: check-manifest
args: ["--no-build-isolation"]
- repo: https://github.com/pre-commit/mirrors-prettier
rev: "v2.6.0"
rev: "v2.6.2"
hooks:
- id: prettier
types: [markdown]
Expand Down
13 changes: 6 additions & 7 deletions abcattrs/abcattrs.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
from typing import Iterable
from typing import TypeVar
from typing import get_args
from typing import get_origin

from .type_hints import extract_annotated
from .type_hints import get_resolvable_type_hints

_abstract_marker: Final = object()
Expand All @@ -18,17 +18,16 @@


def get_abstract_attributes(cls: type) -> Iterable[tuple[str, type]]:
hints = get_resolvable_type_hints(cls)

for var, hint in hints.items():
if not get_origin(hint) is Annotated:
for var, hint in get_resolvable_type_hints(cls).items():
annotated = extract_annotated(hint)
if not annotated:
continue
# Checking for both the abstract marker and the type alias itself allows both
# a concise way using e.g. `var: Abstract[int]` as well as a verbose way that
# allows combining the qualifier with other annotated types and qualifiers, e.g.
# `var: Annotated[int, Abstract, Other]`.
if {_abstract_marker, Abstract} & set(get_args(hint)):
yield var, hint
if {_abstract_marker, Abstract} & set(get_args(annotated)):
yield var, annotated


C = TypeVar("C")
Expand Down
20 changes: 20 additions & 0 deletions abcattrs/type_hints.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
from typing import Annotated
from typing import ClassVar
from typing import Final
from typing import ForwardRef
from typing import get_args
from typing import get_origin
from typing import get_type_hints

max_iterations: Final = 10_000
Expand Down Expand Up @@ -32,3 +36,19 @@ def get_resolvable_type_hints(cls: type) -> dict[str, type]:
f"Exceeded {max_iterations} iterations trying to resolve type hints of "
f"{cls.__module__}.{cls.__qualname__}."
)


def extract_annotated(hint: type) -> type | None:
# Unwrap ClassVar[T] -> T.
if get_origin(hint) is ClassVar:
try:
(hint,) = get_args(hint)
# Wrong-argument ClassVars are very hard to produce at runtime, so pragma is
# reasonable here.
except ValueError: # pragma: no cover
return None

if not get_origin(hint) is Annotated:
return None

return hint
17 changes: 16 additions & 1 deletion tests/test_decorator.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import abc
from typing import Annotated
from typing import ClassVar
from unittest import mock

import pytest
Expand Down Expand Up @@ -43,7 +44,21 @@ class A(abc.ABC):
type("B", (A,), {})


def test_can_combine_annotations() -> None:
def test_can_combine_qualifier_with_class_var() -> None:
@abstractattrs
class A(abc.ABC):
foo: ClassVar[Abstract[int]]

with pytest.raises(
UndefinedAbstractAttribute,
match=r"^Concrete class 'B' must define abstract class attribute 'foo'\.$",
):
type("B", (A,), {})

assert not {"foo"} ^ A.__abstract_attributes__ # type: ignore[attr-defined]


def test_can_combine_qualifier_with_annotated() -> None:
other_annotation = object()

@abstractattrs
Expand Down

0 comments on commit bf569ca

Please sign in to comment.