Type[...] doesn't work correctly with unions
Nobody has claimed this yet.
Assessment
- Difficulty
- 5/5
- Estimated time
- Over a week
- Newbie friendliness
- 25/100
Research direction
No files or tests are named. Start by reproducing the two reveal_type examples for str and Optional[str], then investigate how mypy handles generic Type[T] calls with Union types. Done means the reported structure call infers the union or optional type instead of Any without requiring typing.cast.
Written by the indexing model from the issue text.
Description
I have a function called structure(json_obj, type) it takes a json like object and does some stuff to it and, if it can, returns an instance of type, otherwise it raises an error.
But it also supports Union and Optional which means a type annotation like
def structure(obj: Any, type: Type[T]) -> T:... doesn't work. (It returns Any for Unions) I see that typing.cast works correctly but I don't really want to have to write x = cast(Optional[str], structure(foo, Optional[str])) all over my code.
Here's some example code:
from typing import Optional, Type, Any, TypeVar
T = TypeVar('T')
def structure(obj: Any, type: Type[T]) -> T:...
reveal_type(structure('foo', str)) # Revealed type is 'builtins.str*'
reveal_type(structure('foo', Optional[str])) # Revealed type is 'Any'
I don't know how this signaling would be done though, without adding something to typing or telling mypy about your method through some other channel, e.g. config file (eww)
@typing.castlike
def structure(obj: Any, type: Type[T]) -> T:...
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- Avg merge
- 1d 18h
- Merged PRs (30d)
- 54
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from python/mypy
-
bug
Difficulty 2/5 1-3 hours Newbie friendliness 75/100
-
bug
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
-
bug
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
-
documentation
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
-
bug topic-configuration topic-error-reporting
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
Similar issues
-
area/auth bug comp/agent P3 platform/discord type/security
Difficulty 2/5 1-3 hours Newbie friendliness 88/100
NousResearch/hermes-agent#117848 ·
-
Difficulty 2/5 1-3 hours Newbie friendliness 74/100
bancolombia/sentinel#23 ·
-
test md OpenCI
Difficulty 2/5 1-3 hours Newbie friendliness 74/100
-
integration:quickjs org:external priority:backlog topic:code-interpreter topic:middleware type:feature
Difficulty 2/5 1-3 hours Newbie friendliness 74/100
langchain-ai/deepagents#6450 ·
-
bug client
Difficulty 2/5 1-3 hours Newbie friendliness 88/100