Skip to content

Checking Generic Type at Runtime #13053

Closed as not planned
Closed as not planned
@samuelstevens

Description

@samuelstevens

Bug Report

When checking the type of a generic, mypy reports an error when (as far as I understand), I am still following the type contract I set.

To Reproduce

from typing import TypeVar

T = TypeVar("T")

def increment(obj: T) -> T:
    if isinstance(obj, int):
        return obj + 1
    else:
        return obj
$ mypy --strict scratch.py
scratch.py:12: error: Incompatible return value type (got "int", expected "T")
Found 1 error in 1 file (checked 1 source file)

Expected Behavior

I expect there to be no error because if obj is an int, then returning an int is the correct behavior.

Actual Behavior

Mypy reports an error.

Your Environment

  • Mypy version used: 0.961
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files): no other config
  • Python version used: 3.9.7
  • Operating system and version: Ubuntu 20.04.4 LTS (GNU/Linux 5.4.0-121-generic x86_64)

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions