Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(core): KORNIA_CHECK_TYPE names a union by its members (Python 3.14); fix the dead kornia.utils link in README_zh-CN (#6149)

Dmytro Mishkinc6110dfe16ef
diff --git a/README_zh-CN.md b/README_zh-CN.md
index 020eb3cc5..aff1cd16e 100644
--- a/README_zh-CN.md
+++ b/README_zh-CN.md
@@ -57,7 +57,8 @@
| [kornia.geometry](https://kornia.readthedocs.io/en/latest/geometry.html) | 执行几何计算的模块,用于使用不同的相机模型执行图像变换、3D线性代数和转换 |
| [kornia.losses](https://kornia.readthedocs.io/en/latest/losses.html) | 损失函数模块 |
| [kornia.morphology](https://kornia.readthedocs.io/en/latest/morphology.html) | 执行形态学操作的模块 |
-| [kornia.utils](https://kornia.readthedocs.io/en/latest/utils.html) | 图像/张量常用工具以及metrics |
+| [kornia.image](https://kornia.readthedocs.io/en/latest/image.html) | 图像数据结构、绘制以及图像/张量常用工具 |
+| [kornia.metrics](https://kornia.readthedocs.io/en/latest/metrics.html) | 评估指标模块 |
## 支持我们
diff --git a/changelog.d/6149.fixed.md b/changelog.d/6149.fixed.md
new file mode 100644
index 000000000..8efddf32c
--- /dev/null
+++ b/changelog.d/6149.fixed.md
@@ -0,0 +1 @@
+`KORNIA_CHECK_TYPE` now names an expected union by its members, such as `expected int | str`, on every Python version. Its error message said `Union` for `typing.Union[...]`, `Optional` for `typing.Optional[...]`, and on Python 3.14 also `Union` for `int | str`.
diff --git a/kornia/core/check.py b/kornia/core/check.py
index 873f4b78b..13001fada 100644
--- a/kornia/core/check.py
+++ b/kornia/core/check.py
@@ -20,7 +20,8 @@
from __future__ import annotations
import os
-from typing import TYPE_CHECKING, Any, Callable, Optional, Sequence, TypeVar, Union, cast
+from types import UnionType
+from typing import TYPE_CHECKING, Any, Callable, Optional, Sequence, TypeVar, Union, cast, get_args, get_origin
import torch
from torch import float16, float32, float64
@@ -301,6 +302,15 @@ def KORNIA_UNWRAP(maybe_obj: Any, typ: Any) -> Any:
_T = TypeVar("_T", bound=type)
+def _type_name(typ: Any) -> str:
+ """Name a type for an error message, spelling a union of any kind as ``int | str``."""
+ # A union's own name says nothing: typing.Union[...] is "Union", and from Python 3.14 on so is ``int | str``, which
+ # has no ``__name__`` before 3.14. Name it from its members instead.
+ if get_origin(typ) in (Union, UnionType):
+ return " | ".join("None" if arg is type(None) else _type_name(arg) for arg in get_args(typ))
+ return getattr(typ, "__name__", repr(typ))
+
+
def KORNIA_CHECK_TYPE(
x: Any, typ: _T | tuple[_T, ...], msg: Optional[CheckMessage] = None, raises: bool = True
) -> bool:
@@ -340,12 +350,7 @@ def KORNIA_CHECK_TYPE(
error_msg += f"\n {msg}"
raise TypeCheckError(error_msg)
# In Python mode, we can safely use type introspection
- # A PEP 604 union (``int | str``) has no ``__name__``; its repr is already readable.
- expected_type_str = (
- " | ".join(getattr(t, "__name__", repr(t)) for t in typ)
- if isinstance(typ, tuple)
- else getattr(typ, "__name__", repr(typ))
- )
+ expected_type_str = " | ".join(_type_name(t) for t in typ) if isinstance(typ, tuple) else _type_name(typ)
type_name = str(type(x))
error_msg = f"Type mismatch: expected {expected_type_str}, got {type_name}."
if msg is not None:
diff --git a/tests/core/test_check.py b/tests/core/test_check.py
index 465297365..2fc5b4c63 100644
--- a/tests/core/test_check.py
+++ b/tests/core/test_check.py
@@ -15,6 +15,9 @@
# limitations under the License.
#
+import re
+from typing import Optional, Union
+
import pytest
import torch
@@ -182,10 +185,22 @@ class TestCheckType:
def test_invalid_raises_false(self):
assert KORNIA_CHECK_TYPE("world", int, raises=False) is False
- @pytest.mark.parametrize("typ", [int | str, (int | str, bytes)])
- def test_invalid_union(self, typ):
+ @pytest.mark.parametrize(
+ "typ, expected",
+ [
+ (int | str, "int | str"),
+ ((int | str, bytes), "int | str | bytes"),
+ (Union[int, str], "int | str"),
+ (int | None, "int | None"),
+ (Optional[int], "int | None"),
+ ],
+ ids=["pep604", "tuple", "typing-union", "pep604-none", "typing-optional"],
+ )
+ def test_invalid_union(self, typ, expected):
+ # A union is named by its members on every Python: typing's unions, and from 3.14 also ``int | str``, are
+ # themselves named "Union".
assert KORNIA_CHECK_TYPE(1.0, typ, raises=False) is False
- with pytest.raises(TypeCheckError, match=r"expected int \| str"):
+ with pytest.raises(TypeCheckError, match=rf"expected {re.escape(expected)}, got"):
KORNIA_CHECK_TYPE(1.0, typ)