8000 Type stubs: `cv2.typing` type aliases don't exist at runtime but are not marked as such · Issue #23782 · opencv/opencv · GitHub
[go: up one dir, main page]

Skip to content
Type stubs: cv2.typing type aliases don't exist at runtime but are 8000 not marked as such #23782
@Avasam

Description

@Avasam

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:

  1. 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 using isinstance.
  2. Use classes instead of type aliases that inherits from the aliased type. Those classes can now be marked as type_check_only.
  3. 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)

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions

    0