Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
tikuma-lsuhsc opened this issue Aug 16, 2024 · 2 comments

Comments

@tikuma-lsuhsc
Copy link

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
Copy link
Member

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.

@JelleZijlstra JelleZijlstra closed this as not planned Won't fix, can't repro, duplicate, stale Aug 16, 2024
@tikuma-lsuhsc
Copy link
Author

tikuma-lsuhsc commented Aug 16, 2024

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants