Skip to content

Conversation

@ay0503
Copy link
Owner

@ay0503 ay0503 commented Dec 8, 2024

Infer Union Types for List Expressions with Heterogeneous Elements

Description:

This PR forces the type inference for list expressions in mypy to correctly infer Union types when a list contains elements of different types that have no common supertype other than object. However, currently this forces this for all list expression type inferences and hence breaks everything else. A pretty quirky fix would be to track any list comprehension accesses since this only happens when a union type list is used in the generator portion of a list comprehension.

Background:

Before, when a list literal was constructed with elements of disparate types without a meaningful common superclass, mypy would default to inferring the list's type as List[object]. This behavior led to type-checking issues in scenarios where a more precise type was expected.

For example:

class A:
    pass

class B:
    pass

a = A()
b = B()

l3: list[A | B] = [x for x in [a, b]]  # This would cause a mypy error

However, while this fixes this issue, it also generalizes the entire list expression inference to be forced as well.

@ay0503 ay0503 force-pushed the bug/force-list-comp-union branch from da03a38 to f5cc357 Compare December 8, 2024 18:21
@lexik04 lexik04 requested review from ErkeXia and lexik04 December 8, 2024 18:35
Copy link
Collaborator

@lexik04 lexik04 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks very well written

Copy link
Collaborator

@vsolskyyy vsolskyyy left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well organized, I like your use of comments. Well done.

Copy link
Collaborator

@ErkeXia ErkeXia left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good and solve the problem. Just wonder when the isinstance(e, ListExpr) branch will be executed in infer_item_type

Copy link
Collaborator

@vsolskyyy vsolskyyy left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well written.

Copy link
Collaborator

@KevnKey KevnKey left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks like a good fix to the issue by inferring directly. I can see the union implementation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants