Skip to content
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

Support option for type inference to default to immutable types when possible #9829

Closed
justinaustin opened this issue Dec 21, 2020 · 2 comments
Labels

Comments

@justinaustin
Copy link

justinaustin commented Dec 21, 2020

Feature

Add an option for mypy, maybe something like --infer-immutable-when-possible, that would cause mypy to infer immutable version of types (like Sequence, Mapping, FrozenSet) instead of mutable (List, Dict, Set)

With this feature turned on the below code:

x = [1, 2, 3]
x.append(4)

mypy would give error: "Sequence[int]" has no attribute "append" as it would infer x to be Sequence[int] instead of List[int]

Pitch

Many developers support the idea of immutability by default for a number of reasons, and adding this option would be a nice way for them to opt-in to some version of this with mypy. Currently if I want my variable x = [1, 2, 3] to be Sequence[int] instead of List[int], I need to explicitly add a Sequence[int] type annotation, which is easy to forget. If I had this feature option turned on, I would instead need to explicitly opt-in to mutability with x: List[int] = [1, 2, 3]

I'd love to find out if this feature is something that would be 1. feasible and 2. welcome in the project. If so, I could take a shot with implementing it!

@eyaler
Copy link

eyaler commented Apr 12, 2022

Sequence does not support add for concatenation, so such inference would prevent more than just mutation. In this case, will the type checker know that the inference is not possible? Also how does the inference option relate to variance? e.g. I imagine callable return types should not change from List to Sequence.

@hauntsaninja
Copy link
Collaborator

There haven't been any other requests for this feature. I think it wouldn't be usable in most Python programs, and could interact surprisingly with narrowing. I think #5756 would be the good, explicit way to do this.

@hauntsaninja hauntsaninja closed this as not planned Won't fix, can't repro, duplicate, stale Aug 13, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants