python / python/mypy

False positive for Union[type, ...] and inspect.isclass()

Open
#16,640 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-type-narrowing
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

When a variable's type is declared as a union that includes type (or typing.Type[...]), mypy does not take into account whether usage of that variable occurs inside of an if inspect.isclass(...) conditional block, leading to false positives.

To Reproduce

gist
playground

Python code
from inspect import isclass

registry: dict[str, type] = {}

def decorator_factory(arg: str | type):
    if isclass(arg):
        registry[arg.__name__.lower()] = arg
        return arg
    else:
        def decorator(cls: type):
            registry[arg] = cls
            return cls
        return decorator
        
@decorator_factory
class Foo:
    pass
        
@decorator_factory("alt")
class Bar:
    pass

Expected Behavior**

mypy reports no errors

Actual Behavior

main.py:11: error: Invalid index type "str | type" for "dict[str, type]"; expected type "str"  [index]
Found 1 error in 1 file (checked 1 source file)

Workaround

Using typing.cast to narrow the union explicitly.

gist
playground

Python code
from inspect import isclass
from typing import cast, TYPE_CHECKING

registry: dict[str, type] = {}

def decorator_factory(arg: str | type):
    if isclass(arg):
        registry[arg.__name__.lower()] = arg
        return arg
    else:
        if TYPE_CHECKING:
            arg = cast(str, arg)
        
        def decorator(cls: type):
            registry[arg] = cls
            return cls
        return decorator
        
@decorator_factory
class Foo:
    pass
        
@decorator_factory("alt")
class Bar:
    pass

Your Environment

  • Mypy version used: 1.7.1
  • Mypy command-line flags: (mypy-play defaults)
  • Mypy configuration options from mypy.ini (and other config files): (mypy-play defaults)
  • Python version used: 3.12

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.

Research direction

Start by running the linked reproducer with mypy and compare the reported error with the expected behavior around inspect.isclass() and Union[type, ...]. Trace the type-narrowing path for inspect.isclass, then add regression coverage for the reproducer and verify that mypy reports no errors without the cast workaround.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.