Skip to content

Can't use Optional[T] as Type[U] #8941

Closed

Description

@tarcisioe

The following code fails with mypy 0.780:

from typing import Type, TypeVar, cast, Optional

T = TypeVar('T')


def read(t: Type[T], text: str) -> T:
    return cast(T, None)  # dummy return just for example code


def main() -> None:
    a = read(Optional[int], "10")
    reveal_type(a)
    b = read(int, "10")
    reveal_type(b)

The output:

$ mypy test.py
test.py:11: error: Argument 1 to "read" has incompatible type "object"; expected "Type[<nothing>]"
Found 1 error in 1 file (checked 1 source file)

This made me notice that, while I thought T was being inferred correctly in 0.770, it wasn't:

$ mypy test.py
test.py:12: note: Revealed type is 'Any'
test.py:14: note: Revealed type is 'builtins.int*'

I use this in some code along with typing_inspect to read input into dataclasses, using their types as a schema. The runtime behaviour is correct, but while I thought mypy was correctly inferring the type, when it is Optional, it isn't.

Maybe there is a better way to write this kind of generic code, though, and I'm on the wrong path here. Although I would expect this to work.

Activity

  1. emmatyping commented on Jun 3, 2020

    @emmatyping
    Member

    Optional is not meant to be used like this. It is not a reified type (not usable in a runtime context like this). You would need to unwrap the Optional[T] into either None or T.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions