Skip to content

Commit 631fba1

Browse files
committed
Fix nitpick error on type annotation
Nitpick was failing on TYPE_CHECKER: ClassVar[TypeChecker] It's not clear what to do about this. `TypeChecker` was imported correctly from `jsonschema._types` and is noted in the doc as `jsonschema.TypeChecker`. We can't import the `jsonschema` name at runtime because that would be circular. To resolve, use `typing.TYPE_CHECKING` to conditionally import `jsonschema` at type-checking time. This avoids the circular import but allows us to write TYPE_CHECKER: ClassVar[jsonschema.TypeChecker] As a result, Sphinx correctly builds a cross-reference from the annotation, the annotation is still accurate, and runtime behavior is left untouched.
1 parent 2474242 commit 631fba1

File tree

2 files changed

+12
-5
lines changed

2 files changed

+12
-5
lines changed

jsonschema/_types.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import annotations
2+
13
import numbers
24
import typing
35

jsonschema/protocols.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
from __future__ import annotations
99

10-
from typing import Any, ClassVar, Iterator
10+
from typing import TYPE_CHECKING, Any, ClassVar, Iterator
1111
import sys
1212

1313
# doing these imports with `try ... except ImportError` doesn't pass mypy
@@ -22,8 +22,13 @@
2222
else:
2323
from typing_extensions import Protocol, runtime_checkable
2424

25-
from jsonschema._format import FormatChecker
26-
from jsonschema._types import TypeChecker
25+
# in order for Sphinx to resolve references accurately from type annotations,
26+
# it needs to see names like `jsonschema.TypeChecker`
27+
# therefore, only import at type-checking time (to avoid circular references),
28+
# but use `jsonschema` for any types which will otherwise not be resolvable
29+
if TYPE_CHECKING:
30+
import jsonschema
31+
2732
from jsonschema.exceptions import ValidationError
2833
from jsonschema.validators import RefResolver
2934

@@ -72,7 +77,7 @@ class Validator(Protocol):
7277

7378
#: A `jsonschema.TypeChecker` that will be used when validating
7479
#: :validator:`type` properties in JSON schemas.
75-
TYPE_CHECKER: ClassVar[TypeChecker]
80+
TYPE_CHECKER: ClassVar[jsonschema.TypeChecker]
7681

7782
#: The schema that was passed in when initializing the object.
7883
schema: dict | bool
@@ -81,7 +86,7 @@ def __init__(
8186
self,
8287
schema: dict | bool,
8388
resolver: RefResolver | None = None,
84-
format_checker: FormatChecker | None = None,
89+
format_checker: jsonschema.FormatChecker | None = None,
8590
) -> None:
8691
...
8792

0 commit comments

Comments
 (0)