Skip to content

Narrowed down types sometimes not propagated to lambda #4297

Closed

Description

@JukkaL

The errors generated for the following code are invalid (when using --strict-optional):

from typing import Optional, Callable

def f1(key: Callable[[], str]) -> None: ...
def f2(key: object) -> None: ...

def g(b: Optional[str]) -> None:
    if b:
        f1(lambda: b.upper())  # Item "None" of "Optional[str]" has no attribute "upper"
        z: Callable[[], str] = lambda: b.upper()  # Item "None" of "Optional[str]" has no attribute "upper"
        f2(lambda: b.upper())  # No error
        lambda: b.upper()  # No error

My hypothesis is that callable type context for lambda somehow affects how type narrowing behaves.

This was reported by @tueda on Gitter.

Activity

  1. ikonst commented on Dec 31, 2018

    @ikonst
    Contributor

    Workaround:

    def g(b: Optional[str]) -> None:
        if b:
            _b = b  # https://github.com/python/mypy/issues/4297
            f1(lambda: _b.upper())
  2. calimeroteknik commented on Sep 19, 2019

    @calimeroteknik

    This also seems to happen with native collection types whose size is "runtime" (i.e. recursive types in lambda-calculus terms), but not tuples (whose size is "fixed").

    Error / non-error cases added for reproduction, based on the original post:

    from typing import Optional, Callable
    
    def f1(key: Callable[[], str]) -> None: ...
    def f2(key: object) -> None: ...
    
    def g(b: Optional[str]) -> None:
        if b is not None:
            f1(lambda: b.upper())  # Item "None" of "Optional[str]" has no attribute "upper"
            z: Callable[[], str] = lambda: b.upper()  # Item "None" of "Optional[str]" has no attribute "upper"
            d = { "foo": lambda: b.upper() }  # Item "None" of "Optional[str]" has no attribute "upper"
            l = [ lambda: b.upper() ]  # Item "None" of "Optional[str]" has no attribute "upper"
            t = ( lambda: b.upper(), ) # No error
            f2(lambda: b.upper())  # No error
            lambda: b.upper()  # No error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions