Skip to content

Inconsistent feeling handling of Any in binder #20870

Open

Description

@hauntsaninja
from typing import Any, Final

CONSTANT: Final = 2015

def good(result: dict[str, Any]) -> None:
    code = 'asdf'
    if isinstance(result, dict):
        code = result.get('code', code)
    reveal_type(code)  # N: Revealed type is "Any"
    if code == CONSTANT:
        reveal_type(code)  # N: Revealed type is "Any"

def bad(result: Any) -> None:
    code = 'asdf'
    if isinstance(result, dict):
        code = result.get('code', code)
    reveal_type(code)  # N: Revealed type is "builtins.str"
    if code == CONSTANT:
        reveal_type(code)  # N: Revealed type is "builtins.str"

Based on real world code for rotki

This feels a little inconsistent / violating of gradual typing
Not exactly sure what if anything we should do, though

Found this via #20660 which makes --warn-unreachable flag raise a diagnostic on the second comparison

Activity

  1. ilevkivskyi commented on Feb 23, 2026

    @ilevkivskyi
    Member

    I vaguely remember discussion with @cdce8p about this, and IIRC he said that your bad() is actually good (and vice versa). The current behavior w.r.t. Any in binder is a result of many compromises. At some point I tried to make it proper and principled (which is actually not hard by itself), but I lost, because people were not happy with getting more possible false negatives.

  2. ilevkivskyi commented on Feb 23, 2026

    @ilevkivskyi
    Member

    Btw this works (much) better with --allow-redefinition-new. For last two reveals I am getting

    test.py:19: note: Revealed type is "builtins.str | Any"
    test.py:21: note: Revealed type is "Any | Literal[2015]?"
    
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

    bugmypy got something wrongtopic-type-narrowingConditional type narrowing / binder

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions