-
-
Notifications
You must be signed in to change notification settings - Fork 56.2k
Description
System Information
OpenCV python: opencv_python_headless-4.7.0+772599a-cp37-abi3-win_amd64.whl
Operating System / Platform: 10.0.19045 Build 19045
Python version: 3.9.13
Detailed description
Trying to use cv2.typing.anything
at runtime will throw an AttributeError
(ie: AttributeError: module 'cv2.typing' has no attribute 'MatLike'
). The details of when that's the case will depend on the python version and its annotations parser.
This makes the cv2.typing
module dangerous to use, because static type checkers will find its use acceptable.
The @typing.type_check_only
decorator exists for those exact cases, but unfortunately can't be used with type aliases.
There's a couple possible solutions for this, here's some I can think of:
- Make them exist at runtime. This could be as simple as creating a
cv2/typing/__init__.py
where all the values are assigned the type (but without generic typing to support python < 3.9). This has the added bonus of making them runtime-comparable usingisinstance
. - Use classes instead of type aliases that inherits from the aliased type. Those classes can now be marked as
type_check_only
. - Use
typeshed
's workaround of making them private. Not great imo but at least is serves as a reminder for users that these don't exist at runtime.
Steps to reproduce
Here's a example that fails in python 3.9. An older version like 3.6-3.7 would have more cases.
from typing import cast
import cv2.typing
# Let's pretend this came from a method that returns a MatLike, but isn't typed correctly
foo = object()
bar = cast(cv2.typing.MatLike, foo)
Traceback (most recent call last):
File "c:\Users\Avasam\Desktop\import cv2.py", line 6, in <module>
bar = cast(cv2.typing.MatLike, foo)
AttributeError: module 'cv2.typing' has no attribute 'MatLike'
Issue submission checklist
- I report the issue, it's not a question
- I checked the problem with documentation, FAQ, open issues, forum.opencv.org, Stack Overflow, etc and have not found any solution
- I updated to the latest OpenCV version and the issue is still there
- There is reproducer code and related data files (videos, images, onnx, etc)