-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
False positive [union-attr] #16429
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
Comments
The problem here is that mypy doesn't narrow expressions of the form |
I think issues like this have previously been closed because mypy is working as intended here. As you said, mypy doesn't support narrowing of index expressions with dynamic (non-literal) subscripts. This is also true of other Python type checkers — and static type checkers and compilers in other languages. It's difficult (impossible in the general case) to statically prove that a dynamic subscript expression refers to the same element when that expression appears in multiple places within a function. The recommended approach is to use an assignment expression (walrus operator) to assign the element to a local variable. 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 (item := lists[i]) is None:
continue
assert node is not None
node.next = item
node = item
if item.next is not None:
lists[i] = item.next
heapq.heappush(heap, (item.next.val, i))
return head.next |
Thanks for your comments. I quickly checked that @erictraut's updated code indeed doesn't have the violations, although I've to say that writing To a human, this workaround isn't an improvement, but I understand the reasoning "It's difficult to statically prove that a dynamic subscript expression refers to the same element" for a machine. Perhaps this issue can be documented as a known limitation with a workaround available? |
Duplicate of #7339 |
Solving LeetCode 23. Merge k Sorted Lists locally.
To Reproduce
Expected Behavior
No violations. Suppression shouldn't be required.
Actual Behavior
These lines correspond to the
if lists[i].next is not None
block. Note thatlists[i]
has already been checked, and even iflists[i] is not None
is added to theif
condition, the errors don't go away.Your Environment
--strict
mypy.ini
(and other config files):The text was updated successfully, but these errors were encountered: