python / typing_extensions

Backported and experimental type hints for Python
Other
425 stars 106 forks source link

TypeError: unsupported operand type(s) for |: 'type' and 'types.GenericAlias' #445

Closed tikuma-lsuhsc closed 1 month ago

tikuma-lsuhsc commented 1 month ago

I don't know if this is my doing or a bug, but I encountered the error message in the title for my custom typing.py submodule:

from __future__ import annotations
from typing_extensions import *

MediaType = Literal["v", "a", "s", "d", "t", "V"]

class StreamSpec_Options(TypedDict):
    media_type: NotRequired[MediaType]
    file_index: NotRequired[int]
    program_id: NotRequired[int]
    group_index: NotRequired[int]
    group_id: NotRequired[int]
    stream_id: NotRequired[int]

class StreamSpec_Index(StreamSpec_Options):
    index: int

class StreamSpec_Tag(StreamSpec_Options):
    tag: str | tuple[str, str]

class StreamSpec_Usable(StreamSpec_Options):
    usable: bool

StreamSpec = StreamSpec_Index | StreamSpec_Tag | StreamSpec_Usable # <<= error on this line

This works in py3.11. I initially only had __future__ import in place anticipating the compatibility issue for earlier Python versions. With NotRequired removed, it failed with plain typing.py with a different error message:

TypeError: unsupported operand type(s) for |: '_TypedDictMeta' and '_TypedDictMeta'

So, the difference in the error messages with/without typing_extensions makes me think that it's trying to support this annotation but something is off.

Is this a bug or am I doing something wrong? Thanks!

JelleZijlstra commented 1 month ago

You don't say what version of Python is giving you errors, but support for creating unions using | was added only in Python 3.10. typing_extensions does not attempt to support this feature on older versions, because it relies on a change in the core language (the addition of an __or__ method to builtins.type) that we cannot backport.

from __future__ import annotations does not matter for what you are doing because the place where you're seeing the error is not an annotation.

tikuma-lsuhsc commented 1 month ago

@JelleZijlstra -

Sorry, I was testing on py3.8 and py3.9.

what you are doing because the place where you're seeing the error is not an annotation.

Ah, this makes sense. I switched over to Union[...] and that resolved the issue. Thank you for your feedback.