Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

issubclass() assertions not narrowing types #10680

Open
jwodder opened this issue Jun 20, 2021 · 2 comments
Open

issubclass() assertions not narrowing types #10680

jwodder opened this issue Jun 20, 2021 · 2 comments
Labels
bug mypy got something wrong topic-type-narrowing Conditional type narrowing / binder

Comments

@jwodder
Copy link

jwodder commented Jun 20, 2021

Consider the following (contrived) code:

from typing import Type

def untyped_function():
    return int

def foo() -> Type[int]:
    x = untyped_function()
    assert issubclass(x, int)
    return x

Running mypy on this with the --warn-return-any option produces the error "Returning Any from function declared to return "Type[int]"", even though the assert issubclass should convince mypy that x is of type Type[int] and not an Any.

Your Environment

  • Mypy version used: 0.902
  • Mypy command-line flags: --warn-return-any
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: Python 3.9.5
  • Operating system and version: macOS 11.3.1
@jwodder jwodder added the bug mypy got something wrong label Jun 20, 2021
@JelleZijlstra JelleZijlstra added the topic-type-narrowing Conditional type narrowing / binder label Mar 19, 2022
@kveretennicov
Copy link

We hit this issue in production code.

mypy Playground gist with repro and a workaround: https://mypy-play.net/?mypy=latest&python=3.10&gist=35deff0d7118af72d07a113a1f05c82b (mypy 0.961, Python 3.10)

@GertyP
Copy link

GertyP commented Jul 3, 2023

Just in case it's a useful test-case, I have a slight variation on this error, where it's clear from looking that we can deduce the narrowed return type in all conditional paths but where mypy complains that it thinks we could potentially be dealing with an 'Any' type -

def f(something: bool) -> dict:
    my_dict = None
    if something:
        exec('d = {}', globals(), locals())
        my_dict = locals()['d']
        assert isinstance(my_dict, dict)
        # ... No good if we use this assert.
    else:
        my_dict = {}
    # assert isinstance(my_dict, dict)
    # ... but all good if we use this assert
    return my_dict

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-type-narrowing Conditional type narrowing / binder
Projects
None yet
Development

No branches or pull requests

4 participants