Type[...] doesn't work correctly with unions

Open
#4,625 4 comments 4 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
25/100
Issue type
Feature
Clarity
Needs clarification
Activity status
Stale
Tech stack
python
Domain
devtools

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

bug priority-1-normal topic-union-types

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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from python/mypy

All issues in python/mypy

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.