Skip to content

Inference of Any against optional type infers Never #8829

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

Open
rggjan opened this issue May 15, 2020 · 3 comments
Open

Inference of Any against optional type infers Never #8829

rggjan opened this issue May 15, 2020 · 3 comments
Labels
bug mypy got something wrong priority-0-high topic-type-narrowing Conditional type narrowing / binder topic-type-variables

Comments

@rggjan
Copy link

rggjan commented May 15, 2020

See the following example:

from typing import Any, Optional, TypeVar

T = TypeVar("T")


def assert_not_none(value: Optional[T]) -> T:
    assert value is not None
    return value


def foo1(a: Optional[Any]) -> int:
    return assert_not_none(a)[3]


def foo2(a: Optional[Any]) -> int:
    assert a is not None
    return a[3]

I would expect that foo1 and foo2 are equivalent. However, running mypy on this file, I get:

test.py:12: error: Value of type <nothing> is not indexable

For some reason, assert_not_none doesn't map Optional[Any] to Any, as it is supposed to (and which would accept the indexing), but instead maps it to <nothing> which throws an error. The second version with asserting that it is not None seems to work fine, though.

@msullivan msullivan added bug mypy got something wrong priority-1-normal labels May 20, 2020
@msullivan
Copy link
Collaborator

Definitely a bug and a somewhat surprising one too. Probably an issue in constraints.py?

@AlexWaygood AlexWaygood added topic-type-variables topic-type-narrowing Conditional type narrowing / binder labels Mar 27, 2022
@ilevkivskyi
Copy link
Member

The root cause is:

a: Any
def assert_not_none(value: Optional[T]) -> T: ...
reveal_type(assert_not_none(a))  # Revealed type is "Never"

(and same with Optional[Any]) because of loose handling of unions in constraints.py. This is pretty bad IMO, so raising priority to high.

@ilevkivskyi ilevkivskyi changed the title Value of type <nothing> is not indexable Inference of Any against optional type infers Never Feb 8, 2025
@JukkaL
Copy link
Collaborator

JukkaL commented Apr 30, 2025

I encountered this when preparing an internal codebase for the 1.16 release. The issue wasn't directly related to any change in 1.16, though -- some additional Any | None types are inferred after recent changes.

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

No branches or pull requests

5 participants