Skip to content

Inconsistent inference of sum return type when coupled with nullability. #7287

Closed
@Sean1708

Description

@Sean1708

Please provide more information to help us understand the issue:

  • Are you reporting a bug, or opening a feature request? Bug

  • Please insert below the code you are checking with mypy,
    or a mock-up repro if the source is private. We would appreciate
    if you try to simplify your case to a minimal repro.

    from typing import Optional
    
    
    def foo() -> int:
        return sum([])
    
    
    reveal_type(sum([]))
    
    
    def test1(a: Optional[int]) -> None:
        b = a
        if b is None:
            b = sum([])
    
        reveal_type(b)
    
    def test2(a: Optional[int]) -> None:
        b = a
        if b is None:
            b = foo()
    
        reveal_type(b)
    
    def test3() -> None:
        b = None
        if b is None:
            b = sum([])
    
        reveal_type(b)
    
    def test4(a: Optional[int]) -> None:
        if a is None:
            b = sum([])
        else:
            b = a
    
        reveal_type(b)
  • What is the actual behavior/output?

    $ mypy test.py
    test.py:8: note: Revealed type is 'builtins.int'
    test.py:16: note: Revealed type is 'Union[builtins.int, None]'
    test.py:23: note: Revealed type is 'builtins.int'
    test.py:30: note: Revealed type is 'builtins.int'
    test.py:38: note: Revealed type is 'builtins.int'
    
  • What is the behavior/output you expect? I expect b to be inferred as an int in all cases, i.e.:

    $ mypy test.py
    test.py:8: note: Revealed type is 'builtins.int'
    test.py:16: note: Revealed type is 'builtins.int'
    test.py:23: note: Revealed type is 'builtins.int'
    test.py:30: note: Revealed type is 'builtins.int'
    test.py:38: note: Revealed type is 'builtins.int'
    
  • What are the versions of mypy and Python you are using?

    $ python3.7 --version
    Python 3.7.2
    $ mypy --version
    mypy 0.720
    

    Do you see the same issue after installing mypy from Git master? Yes (mypy 0.730+dev.eb34a7bdcceb4507459c0ef5472117f65bd0855d)

This might be a duplicate of #6697, but the details differ enough that I thought I should open a ticket just in case.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions