Skip to content

False positive [union-attr] #16429

Closed as not planned
Closed as not planned
@asarkar

Description

@asarkar

Solving LeetCode 23. Merge k Sorted Lists locally.

You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.

Merge all the linked-lists into one sorted linked-list and return it.

To Reproduce

import heapq
from typing import Optional

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def merge_k_lists(lists: list[Optional[ListNode]]) -> Optional[ListNode]:
    heap = [(ll.val, i) for i, ll in enumerate(lists) if ll is not None]
    heapq.heapify(heap)
    head = ListNode(0)
    node: Optional[ListNode] = head
    while heap:
        _, i = heapq.heappop(heap)
        if lists[i] is None:
            continue
        assert node is not None
        node.next = lists[i]
        node = lists[i]
        if lists[i].next is not None:  # type: ignore[union-attr]
            lists[i] = lists[i].next  # type: ignore[union-attr]
            heapq.heappush(heap, (lists[i].val, i))  # type: ignore[union-attr]
    return head.next

Expected Behavior
No violations. Suppression shouldn't be required.

Actual Behavior

linked_lists/functions.py:123: error: Item "None" of "ListNode | None" has no attribute "next"  [union-attr]
linked_lists/functions.py:124: error: Item "None" of "ListNode | None" has no attribute "next"  [union-attr]
linked_lists/functions.py:125: error: Item "None" of "ListNode | None" has no attribute "val"  [union-attr]

These lines correspond to the if lists[i].next is not None block. Note that lists[i] has already been checked, and even if lists[i] is not None is added to the if condition, the errors don't go away.

Your Environment

  • Mypy version used: 1.6.1
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files):
    [tool.mypy]
    exclude = [
      'venv'
    ]
    ignore_errors = 'False'
    
  • Python version used: 3.11

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